Understanding custom events
Creating and using custom events are not a big deal in JavaScript—all of the major JavaScript libraries heavily depend on their own events to make their components loosely coupled. Each component possesses a set of custom events for better reusability and integration with the application.
Creating a custom event in Backbone is quite simple—any object that extends the Backbone.Events
class gets all of the event-related functionality, that is, listening to, triggering, and removing events. Backbone's View
, Model
, Collection
, and Router
are the major components that extend the Backbone.Events
class, and you can fire a custom event on any one of them when needed:
var myView = new Backbone.View(); myView.on('myevent', function () { console.log('"myevent" is fired'); }); myView.trigger('myevent');
Here we create a Backbone view instance, register a custom event to it, and fire the event. Once the event is fired, the registered function runs immediately as expected.