Chad Johnson
Chad Johnson

Reputation: 21895

Backbone "success" callback vs. model "change" event binding purposes

What is the purpose of the "success" callback when fetching data for a model vs. the purpose of binding to a method for the "change" event?

"success" callback

this.model.fetch({
  url: '...'.

  success: function(response) {
    ...
  }
});

vs. model "change" binding

this.model.bind("change", this.attributesChanged);

Upvotes: 3

Views: 2740

Answers (3)

monkeyboy
monkeyboy

Reputation: 542

The 'change' event will fire if the model is updated by any method, for example user input into a form which is used to change a model attribute, or fetching data from the server.

The success callback on fetch is obviously called only after fetching from the server.

So if you only want to respond to changes to the model caused by fetches, rather than 'bidirectional' changes, use a success handler rather than a change event.

Upvotes: 0

Anthony Chua
Anthony Chua

Reputation: 1198

Usually i use fetch-success callback in cases when i call fetch outside of the model itself and want an additional success function callback triggered in the model.

Also on a note, be careful with CRUD events though, as "change" events may still be trigger even when its unsuccessful in storing to the server, remember "change" is triggered when the model is changed. As of version 0.9.0, a "sync" event has been added to address this issue. This triggers whenever a model's state has been successfully synced with the server.

Upvotes: 7

Brendan Delumpa
Brendan Delumpa

Reputation: 1145

The main reason to use "success" or "error" for that matter, is to execute functionality based upon the response as "change" will only fire on successful change of the model. If your fetch failed for some reason, "change" won't fire. The callbacks allow you a bit finer level of control. That said, it kind of boils down to personal preference as to when you want to respond to the response. My thought is that if I am only interested in doing something in response to a successful CRUD operation, then listening for "change" is entirely appropriate, as I will just ignore errors.

Upvotes: 2

Related Questions