iririr
iririr

Reputation: 261

Backbone model after successful save

I have a Backbone model object which I successfully save. However the response from the server once the object is saved is another object (not the same object I am saving (not my decision, it's a system I have to deal with)):

var userActivity = new UserActivity();

...some other logic here...

userActivity.save(null, {
    wait: true,
    success: function(model, response, options) {
        dataLoader.getCachedObject(
            function(cachedObject) {
                // I want to update cachedObject object with new data coming back from the server, in a way that my views get updated on change event.
            });
        },
        error: function(model, xhr, options){
    }
});

I want to update cachedObject object with new data coming back from the server, in a way that my views get updated on change event.

How can I accomplish that? Do I call

cachedObject.parse(response)

Any help is greatly appreciated.

Upvotes: 0

Views: 955

Answers (1)

David Sulc
David Sulc

Reputation: 25994

If I understand you correctly, each time your model successfully syncs with the server, you want to update the client-side attributes with the data coming from the server, right? You should be able to do it with something like this:

In your model:

initialize: function(){
  this.on("sync", function(model, response, options){
    this.set(response.newData);
  }
}

Of course, change the newData key to whatever object the server uses to return the dat you want...

Now, each time the model successfully sync with the server, it will set its attributes to what is returned by the server, which will trigger a "change" event.

In your view, you can then have

initialize: function(){
  this.listenTo(model, "change", this.render);
}

And the view wil rerender itself each time the models changes (which will happen after each save on the server).

Upvotes: 1

Related Questions