I'm trying to understand how to create objects and methods with Backbone. I started with something like this:
Person = (function () {
return Backbone.Model.extend({
defaults: {
name: 'jon'
},
changeName: function (newName) {
console.log(newName);
this.name = newName;
}
});
})();
var p1 = new Person();
console.log(p1.get('name'));
p1.changeName("samanatha");
console.log(p1.get('name'));
What I don't understand is, why doesn't my p1.name property change. I thought it had something to do with "this" in this.name since I'm still trying to grasp how 'this' works, but I think I'm missing something else since this.name = newName and name=newName both do not work. Thanks!
2 Answers 2
name is contained in the attributes of your model: p1.attributes.name. That's why you access it using get(). If you want to change name, you can do one of the following:
p1.set("name", "samantha")
p1.set({"name": "samantha"})
By passing in an object, the latter allows you to set multiple attributes at once.
According to the docs:
Please use set to update the attributes instead of modifying them directly.
This is so Backbone can do things like trigger a change event when you change an attribute, or provide a serialized version of the attributes when you call toJSON().
Comments
...
changeName: function (newName) {
console.log(newName);
this.name = newName;
}
...
Should be
...
changeName: function (newName) {
console.log(newName);
this.set ({'name': newName});
}
...