【发布时间】:2014-07-16 03:55:06
【问题描述】:
我正在尝试在我的 Backbone 视图的渲染函数中包含一个可选参数,如下所示:
var AppView = Backbone.View.extend({
el: '#app',
initialize: function(){
_.bindAll(this,'render');
this.listenTo(app.collection.sellables,'reset', this.render);
},
render: function(sellableId){
if(typeof sellableId == "undefined"){
var sellable = app.collection.sellables.first();
}
else{
var sellable = app.collection.sellables.get(sellableId);
}
var view = new SellableView({model: sellable});
this.$('#sellables').append(view.render().el);
},
});
第一次呈现这个视图时,它发生是因为app.collection.sellables 集合在从服务器接收到一些数据后被重置。当此重置发生时,视图的渲染函数被调用,但不是以 sellableId 未定义的方式调用,而是 sellableId 等于 app.collection.sellables 变量,这会导致错误。为了澄清,视图的渲染函数被调用是因为:
app.collection.sellables.reset(data.skus);
为什么我的渲染函数会接收集合作为参数而不是未定义的参数?
另外,如果我手动渲染视图,它可以正常工作,并且 sellableId 参数未按预期定义:
var app.view.app = new AppView;
app.view.app.render();
【问题讨论】: