Javascript 主干视图+;延迟手柄模板加载
我试图加载把手模板并通过延迟对象/承诺呈现它们,但当我通过添加延迟来重构代码时,出现了错误: 我的看法如下:Javascript 主干视图+;延迟手柄模板加载,javascript,jquery,backbone.js,jquery-deferred,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){
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;
}
});
var indexView=Backbone.View.extend({
初始化:函数(选项){
this.options=options |{};
getTemplate('path/to/template')。然后(函数(tpl){
//tpl是一个handlebar编译的模板,由getTemplate返回
该模板=第三方物流;
这个。render();
//这导致
//未捕获的TypeError:对象#没有方法“render”
//“这”是Backbone.View.extend.initialize
});
},
渲染:函数(){
//此.options未定义
this.el.html(this.template(this.options.data));
归还这个;
}
});
我无法理解如何从.then()函数访问this.render,以及为什么在render()函数中this.options现在未定义
谢谢你小心这个的恶性!当调用延迟函数时,它可能不是您认为的那样,特别是在涉及jQuery的情况下 试一试
@hiral感谢您纠正我的语法,我没有注意到错误。对JavaScript上下文进行一些研究,这是一个值得了解的有趣主题。另外,在异步调用之前,只需将
this
放入一个var中:var self=this代码>。然后在回调中使用self
。(问题是,你的匿名函数不是你的视图方法,所以它不知道你的视图)我猜这是一个好的开始:)@Stormsson欢迎:)@Loamhoof你的评论解决了我的问题!这很简单!我甚至尝试了$.proxy(),但没有成功,但我只需要使用self保存上下文!:D如果你回答正确,我会选择这个作为答案accepted@Stormsson尼可什的回答也是一样,接受他的回答。(即使我不得不说我并不真的同意jQuery的评论,这个问题与jQuery没有真正的联系,而且更一般)。顺便说一句,另一个解决方案是使用bind
的functions方法绑定上下文:(function(){}).bind(this)
。
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();
});
}