Backbone.js 使用主干渲染把手模板
我有一个基本观点(见下文),我相信这是正确的Backbone.js 使用主干渲染把手模板,backbone.js,handlebars.js,Backbone.js,Handlebars.js,我有一个基本观点(见下文),我相信这是正确的 Index = Backbone.View.extend({ render: function() { var activities = new Activities(); activities.fetch(); var tpl = Handlebars.compile($("#activities-template").html()); $(this.el).html(tpl({act
Index = Backbone.View.extend({
render: function() {
var activities = new Activities();
activities.fetch();
var tpl = Handlebars.compile($("#activities-template").html());
$(this.el).html(tpl({activities: activities.toJSON()}));
return this;
}
});
如果使用Chrome JS控制台执行render()函数中的每一行,我将得到预期的结果,并用模板输出填充传入的元素。但是,当我使用下面的
var i = new Index({el: $("body")})
i.render()
“i.$el”是完全空的——HTML不像在控制台中那样呈现。知道为什么吗?是一个AJAX调用,因此不能保证activities.toJSON()
在执行此操作时会提供任何数据:
activities.fetch();
var tpl = Handlebars.compile($("#activities-template").html());
$(this.el).html(tpl({activities: activities.toJSON()}));
在控制台中执行代码可能会让AJAX调用有时间在您尝试使用活动之前返回一些内容
你应该做两件事:
如果activities
为空,请修复模板以执行一些合理的操作(例如显示某种加载…消息)
将视图的渲染
附加到集合的“重置”
事件:
initialize: function() {
// Or, more commonly, create the collection outside the view
// and say `new View({ collection: ... })`
this.collection = new Activities();
this.collection.on('reset', this.render, this);
this.collection.fetch();
},
render: function() {
var tpl = Handlebars.compile($("#activities-template").html());
this.$el.html(tpl({activities: this.collection.toJSON()}));
return this;
}
我还切换到,$(this.el)
当主干已经给你这个时,就没有必要了。$el
谢谢你的回答!当我实现这个时,我不得不改变一件事:activities.toJSON()
应该是this.collection.toJSON()
,我相信。无论如何,当我进行更改时,无法调用undefined的方法“toJSON”
,因为调用render
时,this.collection
仍然未定义。如果我取出reset
回调处理程序,它就会工作。所以我仔细研究了一下,得出了以下结论(对不起,JSFIDLE):@schleg:this.collection.toJSON(),这就是我没有测试代码的原因。“undefined”错误可能是因为render
未使用\uu.bindAll
绑定,您也可以说this.collection.on('reset',this.render,this))
(注意第三个参数)`就像在我的update.Ah中一样,\uu.bindAll
一直是关键。谢谢--这个问题看起来有点傻,但你是帮助别人的冠军:)谢谢,这很有效。我还尝试了model.attributes,这也很好,但我想toJSON将是使用主干网的更标准的方法。model?@JoshGough:model.toJSON()
是常用的方法(默认情况下只做.clone(model.attributes)
)。