我正面临Backbone.js上的"更改事件未触发"问题= /
这里是我对用户模型的看法:
window.UserView = Backbone.View.extend({
...
initialize: function()
{
this.model.on('destroy', this.remove, this);
this.model.on('change', function()
{
console.log('foo');
});
},
render: function(selected)
{
var view = this.template(this.model.toJSON());
$(this.el).html(view);
return this;
},
transfer: function(e)
{
var cas = listofcas;
var transferTo = Users.getByCid('c1');
var transferToCas = transferTo.get('cas');
this.model.set('cas', cas);
console.log('current model');
console.log(this.model);
//this.model.change();
this.model.trigger("change:cas");
console.log('trigger change');
transferTo.set('cas', transferToCas);
console.log('transferto model');
console.log(transferTo);
//transferTo.change();
transferTo.trigger("change:cas");
console.log('trigger change');
}
});
Run Code Online (Sandbox Code Playgroud)
在这里,用户模型:
window.User = Backbone.Model.extend({
urlRoot: $('#pilote-manager-app').attr('data-src'),
initialize: function()
{
this.set('rand', 1);
this.set('specialite', this.get('sfGuardUser').specialite);
this.set('name', this.get('sfGuardUser').first_name …Run Code Online (Sandbox Code Playgroud) Person = Backbone.Model.extend({
defaults: {
name: 'Fetus',
age: 0,
children: []
},
initialize: function(){
alert("Welcome to this world");
},
adopt: function( newChildsName ){
var children_array = this.get("children");
children_array.push( newChildsName );
this.set({ children: children_array });
}
});
var person = new Person({ name: "Thomas", age: 67, children: ['Ryan']});
person.adopt('John Resig');
var children = person.get("children"); // ['Ryan', 'John Resig']
Run Code Online (Sandbox Code Playgroud)
在此示例代码中,我们有:
children_array = this.get("children")
我以为这只会指向内存中的相同数组(因此也是O(1)).然而,我认为这将是一个设计层,因为可以在不使用this.set()的情况下操纵数组,然后事件监听器就不会触发.
所以我猜它(不知何故神奇地)复制数组?
http://backbonejs.org/#Model-set
怎么了?
编辑:我刚刚在https://github.com/documentcloud/backbone/blob/master/backbone.js的骨干源代码中找到了实现(我在底部粘贴了相关代码)
获得回报:
return this.attributes[attr]
Run Code Online (Sandbox Code Playgroud)
所以这只会指向内存中的相同数组吗?所以可以在不使用set()的情况下更改数组,这样会很糟糕......?我对么?
get: function(attr) {
return this.attributes[attr];
},
// Get …Run Code Online (Sandbox Code Playgroud)