Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What events are triggered when calling fetch() on a Backbone.js collection?

Tags:

backbone.js

In my backbone.js app, there is a Trips collection that holds Trip models, which is working with LocalStorage. I am able to call Trips.create(form_attributes) to create and save a trip to the Todos store.

When I first load my app, I call Trips.fetch({ success: trips_fetch_success }), and trips_fetch_success receives a response that shows the Trip models that the Trips collection holds.

I have tried to bind refresh and change events to the Trips collection, but these events are not being caught, making me believe I have the wrong idea about which events Trips.fetch triggers.

My question: which events should Trips.fetch trigger? And are the events triggered on the collection or on each of the individual Trip models?

like image 678
Alan David Garcia Avatar asked Mar 10 '11 18:03

Alan David Garcia


People also ask

How do I trigger an event in Backbone JS?

js trigger Event is used to invoke or callback the function for the given event or a space-delimited list of events. The subsequent arguments will be passed along to the event callbacks in order to trigger it. Parameter Values: event: It is used to bind an object with an event.

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.

What is collections in Backbone JS?

Advertisements. Collections are ordered sets of Models. We just need to extend the backbone's collection class to create our own collection. Any event that is triggered on a model in a collection will also be triggered on the collection directly.


2 Answers

Collection.fetch() will call reset on success, which in turn will trigger a 'reset' event. Any subscribers to the collections reset event should receive the event.

The key here is "on success." I had this problem, only to discover that backbone was silently swallowing my errors messages. Pass in an error handler that, at least, logs to console.log(), and see what's happening:

trips.fetch({error: function() { console.log(arguments); }}); 

(Note: Old versions of backbone.js will trigger "refresh" instead of "reset")

like image 71
Elf Sternberg Avatar answered Oct 04 '22 14:10

Elf Sternberg


If you are using backbone 1.0, you'll need to pass reset:true in the fetch() call in order to bind with the reset event:

trips.fetch({reset: true}); 
like image 41
jesal Avatar answered Oct 04 '22 15:10

jesal