2012-01-11 66 views
0

我得到这个 “对象”Javascript中的Setter + BackBone这是正确的方法吗?

Person = Backbone.Model.extend({ 
    defaults: { 
     name: 'Fetus', 
     age: 0, 
     children: [] 
    }, 
    initialize: function() { 
     this.bind("change:name", function() { 
      var name = this.get("name"); 
      alert("Changed my name to " + name); 
     }); 
    }, 
    adopt: function(newChildsName) { 
     this.get("children").push(newChildsName); 
    }, 
    setName: function(name) { 
     this.set({ 
      name: name 
     }); 
    } 
}); 

不能设置方法setName就像这样: 我试过,但他们没有工作

setName: function(name){ 
    this.get(name) = name; 
} 

setName: function(name){ 
    this[name].set(name); 
} 

还有别的办法吗?我无法想象原来的方式太难以使用。

+0

就我所知,这是标准的方法,如果有更好的方法,我会让更有经验的骨干用户回答。 – c4urself 2012-01-11 12:58:27

回答

3

为了清楚起见,我将参数名称更改为newName。虽然:

this.set({name: newName}); 

意味着:设置名为namenewName参数(正确的)新值的属性值,这种形式:

setName: function(newName){ 
    this.get(newName) = newName; 
} 

什么都不做。它获得一个属性,其名称在newName参数中提供并返回它。作业没有效果。

在另一方面这样的:

setName: function(newName){ 
    this[newName].set(newName); 
} 

可能会引发错误。 this是一个Backbone模型对象。它包含attributes属性,因此可能:

this.attributes[newName] = newName; 

是比较合理的(更改其名称newName参数传递给newName值然而,在这种情况下,change事件将不会被触发的属性,但让我猜。 ,这是你真正想要的东西:

setAttr: function(name, value){ 
    var diff = {}; 
    diff[name] = value; 
    this.set(diff); 
} 

在这种情况下,您可以拨打:

model.setAttr('id', 7); 

相当于:

model.setAttr({id: 7}); 

和触发器change:id正确。

+0

Exatcly:D谢谢! – 2012-01-11 14:13:54

1

最初的样子对我来说最好。您必须在Backbone的事件系统的模型上调用set()才能正常工作。你的两个例子没有多大意义(即给一个值赋值,并在一个值上而不是在模型上调用set())。

我实际上认为添加你自己的setName方法有点奇怪。任何编程Backbone.js的人都应该知道使用模型实例的内置set()函数来设置属性值。

相关问题