3
votes

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?

2
Not sure if it's required, but does your server return a status code of 201 (created) for the save (POST) request? - Chris Salzberg
It returns 200, which means that the operation was successful. - Logan

2 Answers

1
votes

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.

0
votes

There is error in your code:

person.save(person,{

You should provide object of attributes to your save call or just the options, but not the model itself. Remove person, and check if it works. wait:true should be set, to ensure that you change to a proper data validated by server.