Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Backbone trigger a 'change' event when load data from a local file?

I'm trying to test the change event of backbone collection, using this code:

var Item = Backbone.Model.extend({});
var ItemCollection = Backbone.Collection.extend({
  model: Item,
  url: "data.json"
});
var collection = new ItemCollection();
collection.bind("change", function() {cosole.log("collection changed.");});
collection.fetch();

then I change the json file manually and call collection.fetch() again, no 'change' event happens, is it because I use a local json file or .fetch method cannot trigger 'change' event?

like image 704
dencey Avatar asked Feb 28 '12 09:02

dencey


People also ask

How does Backbone JS work?

Backbone. js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTful JSON interface.

Which function has to be used when you want to trigger the event only once before being removed?

js Event once() The event once method is just like event on method but it causes the bound callback to only fire once before being removed.

Is Backbone a MVC?

Backbone is a JavaScript MVC library and that's a key difference.


1 Answers

Because fetching a collection calls the reset method, a reset event is fired.

fetch collection.fetch([options])
.... When the model data returns from the server, the collection will reset...

reset collection.reset(models, [options])
... Use reset to replace a collection with a new list of models (or attribute hashes), triggering a single "reset" event at the end....

If you specify the option { add: true } in the fetch method, models are added to the collection instead of replacing it, so a add event is fired.


The change event is triggered when a model changes, so basically when the method .set() is called on a model.

like image 148
Didier Ghys Avatar answered Oct 10 '22 18:10

Didier Ghys