I got this “object”
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
});
}
});
Can’t the set method setName be done like this :
I tried but they don’t work
setName: function(name){
this.get(name) = name;
}
or
setName: function(name){
this[name].set(name);
}
Is there another way ? I can’t go around thinking the original way is too ugly to use.
For clarity I am changing the argument name to
newName. While:means: set a value of an attribute named
namewith new value ofnewNameparameter (correct), this form:does nothing. It gets an attribute whose name is provided in
newNameparameter and returns it. The assignment has no effect.On the other hand this:
will probably throw an error.
thisis a Backbone model object. It containsattributesproperty, so probably:is more reasonable (change the attribute whose name is passed in
newNameparameter tonewNamevalue. However in this case thechangeevent won’t be triggered. But let me guess, this is what you really wanted:In this case you can call:
Which is equivalent to:
and triggers
change:idcorrectly.