2

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!

asked Mar 22, 2013 at 5:13

2 Answers 2

5

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().

answered Mar 22, 2013 at 5:20
Sign up to request clarification or add additional context in comments.

Comments

0
...
changeName: function (newName) {
 console.log(newName);
 this.name = newName;
}
...

Should be

...
changeName: function (newName) {
 console.log(newName);
 this.set ({'name': newName});
}
...

http://backbonejs.org/#Model-set

answered Mar 22, 2013 at 5:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.