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
Calling save with new attributes will cause a "change" event immediately, and a "sync" event after the server has acknowledged the successful change. Pass {wait: true} if you'd like to wait for the server before setting the new attributes on the model.
Sounds like the server hasn't returned that it is finished. Removing wait:true should make the changed event trigger.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With