骨干视图+延迟车把模板加载

时间:2014-01-10 09:58:09

标签: javascript jquery backbone.js jquery-deferred

我正在尝试加载把手模板并通过延迟对象/承诺渲染它们,但是当我通过放入延迟重构代码时,错误正在发生:

我的观点如下:

var indexView = Backbone.View.extend({    
    initialize: function (options) {
        this.options = options || {};      
        manager.getTemplate('path/to/template').then(function(tpl){               
            // tpl is a handlebar compiled template,returned by getTemplate
            this.template = tpl;
            this.render();     
        // that causes
        // Uncaught TypeError: Object #<Object> has no method 'render'
        // "this" is Backbone.View.extend.initialize           
        });
    },
    render: function (){
        // this.options is undefined
        this.$el.html(this.template(this.options.data));            
        return this;
    }
});

我无法理解我应该如何从.then()函数到达this.render以及为什么在render()函数中this.options现在是未定义的 谢谢

1 个答案:

答案 0 :(得分:1)

谨防恶意this!调用延迟函数时可能不是您认为的那样,尤其是涉及jQuery的情况。

尝试

initialize: function (options) {
    this.options = options || {};
    var myself = this;

    manager.getTemplate('path/to/template').then(function(tpl){               
        // tpl is a handlebar compiled template,returned by getTemplate
        myself.template = tpl;
        myself.render();
    });
}
相关问题