Book Image

Backbone.js Patterns and Best Practices

By : Swarnendu De
Book Image

Backbone.js Patterns and Best Practices

By: Swarnendu De

Overview of this book

Table of Contents (19 chapters)
Backbone.js Patterns and Best Practices
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Precompiling Templates on the Server Side
Index

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.

Tip...