【发布时间】:2015-07-09 00:59:41
【问题描述】:
我有这个烦人的问题,我感觉这是因为我们不能像使用 Backbone 模型那样使用 Backbone Views 的默认值。我的目标是使用带有 Backbone 视图的默认值,然后根据需要使用传递给初始化函数的选项覆盖它们。我遇到的问题是,当我调用 this.collection Backbone 时,它与 this.defaults.collection 不匹配,正如我所期望的那样。当我在初始化函数中调用 this.collection 时,我得到一个空点异常,即使我在默认值中分配了集合。
也许我需要的是我的初始化函数中的这个调用:
this.options = _.extend(this.defaults, this.options);
然而,在这种情况下,默认值并没有做任何特别的事情。 this.defaults 可以称为 this.cholo。我想我想知道为什么默认值/属性与骨干模型的行为不同。
我有以下代码:
var IndexView = Backbone.View.extend({
el: '#main-div-id',
defaults: function(){
return{
model: null,
collection: collections.users,
childViews:{
childLoginView: null,
childRegisteredUsersView: null
}
}
},
events: {
'click #loginAsGuest': 'onLoginAsGuest',
'click #accountRecoveryId': 'onAccountRecovery'
},
initialize: function (opts) {
this.options = Backbone.setViewOptions(this, opts);
Backbone.assignModelOptions(this,this.options);
_.bindAll(this, 'render', 'onFetchSuccess', 'onFetchFailure');
this.listenTo(this.collection, 'add remove reset', this.render); //this.collection is not defined here
this.collection.fetch({ //null pointer here, this.collection is not defined
success: this.onFetchSuccess.bind(this),
error: this.onFetchFailure.bind(this)
});
},
render: function () {
//removed code because it's extraneous for this example
},
onFetchSuccess: function () {},
onFetchFailure: function () {}
},
{ //classProperties
givenName: '@IndexView'
});
...顺便说一下,为了让每个视图实例的事件不同,我应该把事件变成一个类似于默认值的函数吗?
【问题讨论】:
-
请注意
_.extend修改了它的第一个参数,所以你不想_.extend(this.defaults, ...)因为defaults将在原型上,因此被所有实例共享。你会想要_.extend({ }, this.defaults, ...)。 -
谢谢 我只是想知道为什么第一个参数需要是一个空对象。副作用全效,宝贝。