Backbone Views + deferred handlebars template loading

删除回忆录丶 提交于 2019-12-25 02:43:53

问题


I am trying to load handlebars templates and rendering them via deferred objects / promises, but when i refactored the code by putting in deferreds , errors are occurring:

My view is as follows:

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;
    }
});

i can't understand how i'm supposed to reach this.render from the .then() function and also why in the render() function this.options is now undefined Thank you


回答1:


Beware the malignant this! It may not be what you think it is when your deferred function is called, especially where jQuery is involved.

Try

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();
    });
}


来源:https://stackoverflow.com/questions/21041138/backbone-views-deferred-handlebars-template-loading

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!