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)