Backbone和Handlebars Rendering View with this。$ el.html

时间:2014-05-29 02:06:22

标签: javascript jquery backbone.js handlebars.js

我已开始使用骨干和Handlebars,下面的代码在this.$el.html(jsObject);处中断,并显示下一个错误:

Uncaught TypeError: Cannot read property 'html' of undefined tasks.js:26
(anonymous function) tasks.js:26
fire jquery.js:3119
self.fireWith jquery.js:3231
done jquery.js:9275
callback jquery.js:9685

有一个完成函数允许在JSON.parse进来之前重新获取fetch。我使用JSON.stringifyJSON.parse因为把手需要一个JavaScript对象而我的api返回json(我确定有一个更好的方法)。 console.log(jsObject);提供了生成html的正确把手,所以不确定为什么它会停止,我确实想要做var context = template(jsonObject.toJSON());这样的事情,因为这将适用于代码中的块数据。

编辑:我已将其清除以删除JSON.stringifyJSON.parse,并使用toJSON()并输入完整错误。使用Backbone 1.1.2和JQuery v1.11.1。

var serverUrl           = 'http://test.local/'; 
var Event = Backbone.Model.extend({});

var EventCollection = Backbone.Collection.extend({
    model: Event,
    url: serverUrl + 'events'   
});

var EventListView = Backbone.View.extend({
    el: "#events",
    initialize: function(){
        this.render();              
    },
    render: function () {
        var events = new EventCollection;
        var eventsFetch = events.fetch({
            success : function(data){
                events = ((data));
    //          console.log(events); 
            }       
        });
        eventsFetch.done(function(){
            var template = Handlebars.compile( $("#events-template").html() );
            var rendered = template(events.toJSON());
                console.log(rendered);
            this.$el.html(rendered);
            return this;
        });     
    }
}); 

var EventListView = new EventListView();

HTML

<body>
    <div id="events"></div>
        <script id="events-template" type="text/x-handlebars-template">
            <table>
                {{#each []}} 
                <tr>
                    <td>{{this.event_id}}</td>
                    <td>{{this.entity_id}}</td>
                    <td>{{this.event_title}}</td>
                    <td>{{this.event_desc}}</td>
                    <td>{{this.event_state}}</td>
                    <td>{{this.id}}</td>
                </tr>
                {{/each}}
            </table>
        </script>
<script type="text/javascript" src="js/tasks.js" /></script>
</body>
</html>

2 个答案:

答案 0 :(得分:1)

当您的延迟解析时,似乎您的this引用的范围不正确。试试这个:

var _this = this;
eventsFetch.done(function(){
        var template = Handlebars.compile( $("#events-template").html() );
        var rendered = template(events.toJSON());
            console.log(rendered);
        _this.$el.html(rendered);
        return _this;
    });     

答案 1 :(得分:0)

您可以使用jQuery.proxy来保留范围:

  

eventsFetch.done($.proxy(function(){ var template = Handlebars.compile( $("#events-template").html() ); var rendered = template(events.toJSON()); console.log(rendered); this.$el.html(rendered); return this; }, this));

相关问题