3
votes

I`m starting a project with backbone.js and as you know, my main problem was to figure out a good pattern of coding. However, I would like to know how is the best way to handle messages from ajax callbacks (save, destroy, fetch) for example on success without setting all on the model

What I wish to do is separate some data from model and handle it not as attributes, like for example on model.save() callback json:

{ message: "Successful post", post: { id: 13, text: "test" } }

Here is the code:

post = new Post({..})
post.save({}, { 
  success: function(post, xhr) {
     data = jQuery.parseJSON(xhr.responseText)
     alert(data.message)
  }
})

Is there a better way to do it or I have to leave as attribute? Like:

{ message: "Successful post", id: 13, text: "test" }
1

1 Answers

5
votes

You can override the Model parse method to intercept the data from the response.

In your case you might have something like:

parse : function(resp, xhr) {
  alert resp.message;
  return resp.post;
},

So you could keep the same structure in the JSON you return from the server. In your parse method you can do whatever you want with the additional data just so long as you extract the part that represents the model data and return it from the method.