Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

javascript - Backbone Views + deferred handlebars template loading

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...