I am trying to learn Backbone.js and have stuck at an issue. model.save is not updating my model value, though model.fetch updates the value fine.
Please see my code below and let me know if I am doing anything wrong here:
Model
var Person = Backbone.Model.extend({
url: "CreatePerson",
defaults: {
name: "",
age: 0
},
initialize: function(){
this.on("change:name",function(){
alert("Updated value is: "+this.get("name"));
});
}
});
I am creating an instance of this model on my html page, below is the code:
var person = new Person({name:"manish"});
person.save(person,{
wait: true,
success: function(){
alert("Data saved: "+person.toJSON().name);
},
error: function(){
alert("Sorry, something wrong went with the system");
}
});
person.fetch({
success: function(){
alert("Data Fetched: "+person.get("name"));
}
});
On both save and fetch, I am returning the following JSON data from the server:
{"name":"Logan","age":23}
Interestingly, for save, the change event is not fired and the alert box gives me the old model value (i.e manish), whereas when fetch function executes, the change event is fired and the fetch callback gives me the new value (i.e logan).
Can someone help me in identifying what I am doing wrong here?
From backbonejs.org
http://backbonejs.org/#Model-save
Sounds like the server hasn’t returned that it is finished. Removing wait:true should make the changed event trigger.