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?
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.
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.
Backbone is a JavaScript MVC library and that's a key difference.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With