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

I am trying to test the base collection change event 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, the "change" event does not occur because I use the local json file or the .fetch method cannot trigger the "change" event?

+4
source share
2 answers

Since fetching the collection calls the reset method, the reset event is fired.

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

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

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


The change event is fired when the model changes, so basically when the .set() method is called in the model.

+8
source

The 'change' event receives a trigger when one of the attributes of the collection changes. Even if you modified the file yourself, I could not find any file attributes in the ItemCollection . The two attributes you have are a model object and a string. So I think why the 'change' event is not being raised

0
source

Source: https://habr.com/ru/post/1398779/


All Articles