JavaScript Architecture: Backbone.js Events

12.23.2011

Updated Aug 11, 2012 to reflect current library versions.

Backbone.js is an MVC framework for JavaScript applications (although some legitimately argue it’s not technically MVC). Its purpose is to provide structure to your application so it can be modular, decoupled, and scalable. If you’re not sure why you may need an application framework, please read JavaScript Architecture: The Basics first. Backbone is not a dom manipulation utility, templating engine, or UI component library.

Backbone.js files and documentation can be found here or you can get involved with the source and community at GitHub. At the time of this writing, the unminified, documented code is only about 1,200 lines long so don’t be afraid to dig in and walk through the code itself. Heck, there’s even an annotated version.

Backbone.Events

At the heart of every RIA is the observer pattern (otherwise known as the publisher/subscriber pattern). The observer pattern is a design pattern that allows an object to be notified when another object has something to say, or in other words, has an event which it wishes to broadcast.

DOM elements (links, buttons, containers, etc.) already have the observer pattern natively baked in which is why you can watch for when a button is clicked without using libraries like Backbone or jQuery. However, there are times where we want our own JavaScript objects to trigger/dispatch events and we would normally have to write the implementation of this pattern ourselves. That’s where Backbone comes in. Backbone has this code for you in Backbone.Events.

Backbone.Events provides an implementation of a string-key-based observer pattern. In pseudo-code, it operates as follows. I’ve been changing a lot of poop-holes lately so let’s say I’m coding in object dad and object dad needs to know when object baby drops a turd in its deuce-trap:

var changeDeuceTrap = function() {
	baby.deuces = 0;
	baby.shutCakeHole();
};
 
baby.on('turdDropped', changeDeuceTrap);

And somewhere within baby we have:

this.trigger('turdDropped');

Dad’s telling baby, “Let me know you dropped a turd so I can change your deuce-trap.” If mom had access to the same baby, she could likewise watch for when the baby drops a turd and change the deuce-trap too. If she does so, when the baby drops its next turd we’ll both the notified. In other words, multiple observers can watch for the same event.

You might think this is magic but it’s not. What’s happening here is dad is literally passing the changeDeuceTrap function to baby. Baby then maintains an array for turdDropped and adds changeDeuceTrap to the array. If another observer chooses to listen for the same event, that observer’s function will also be added to the same array inside baby. When baby drops a turd, it iterates through the array calling all the “callback” functions it contains.

While we can easily give any object event-triggering powers using Backbone.Events, don’t worry about it for now. Backbone.Model and Backbone.Collection already have Backbone.Events baked in and those are the main types of objects triggering events in our applications.

I should mention jQuery has an observer pattern implementation of its own but we’ll be focusing on Backbone.

Read more in the Backbone.Events documentation.

<< JavaScript Architecture: Underscore.jsJavaScript Architecture: Backbone.js Models >>

Tags: , , , , ,


Comments

12.24.2011 / Dustin Woodard said:

Hey Aaron, I came across this link http://arturadib.com/hello-backbonejs/ and saw this “shameless ad” for http://agilityjs.com/ any thoughts.

12.25.2011 / David said:

awesome post! thanks alot. i learned sooo much. javascript seemed like a giant decoupled mess but now i’m starting to realize how to approach this beast!

12.25.2011 / Aaron Hardy said:

@Dustin It looks like a decent library. Similar to Backbone in many ways but a different style. I would need to play around with it a bit to give an educated opinion. For enterprise apps, I put a lot of value in healthy communities which can usually be determined by GitHub activity and involvement. I noticed that Agility currently has 410 watchers and 26 forks whereas Backbone has 5,186 watchers and 664 forks, for what it’s worth.

@David Thanks! Glad I could help you out! BTW, I think you meant “coupled” mess. Decoupling is a good thing.

01.04.2012 / khurram said:

Very nice thanks for sharing. I have recently implemented a small backbone application on my website all i am doing there is actually learning backbone.js i have successfully made a single page app and i am gonna extend it now please have a look at Yaqeeni Trades

09.11.2012 / amrita said:

interesting posts, but those variable names, seriously?
yuck and lol.

12.22.2012 / Using Backbone.js « watsonbs said:

[…] Require, Backbone has many pre-existing and excellent tutorials. In particular Artur Adib’s tutorial is what made it all become clear […]

12.31.2012 / Mohit Jain said:

I just started writing a series for backbone js learning and covered the same topic ie listening to dom events in backbone js. It wil great to have your feedback on it, Wrote some 11 articles on learning backbone js series. Really love to have your feedback

http://www.codebeerstartups.com/2012/12/12-listening-to-dom-events-in-backbone-js-learning-backbone-js/

09.09.2013 / MAurĂ­cio said:

Hey, in my company we have an enterprise web app written basically in PHP using jQery as a front-end library for manipulations and such. But recently, the requirements for the app started adding a lot of modal windows, calculations and simulations using javascript code basically.

It’s becoming a HUGE mess, since it grew from a simple .js file into massive interactions in javascript communicating with the backend part.

Is there any MVC front-end framework that allows for better code organization without a rewrite of the app?

Like, for a new feature, add this framework for this part and later on start “migrating” the other parts of the app to this framework..

09.11.2013 / Aaron Hardy said:

Thanks for the question. Yeah, that’s a rough situation but all too common. Backbone is probably the best fit for such a task because it isn’t monolithic at all; you can start using individual portions of the framework without the others and introduce it as much or as little as you want. I would say Backbone’s popularity is fading compared to Angular and Ember these days (all are great frameworks) but for what you’re asking about I still think it’s #1.


Leave a Comment

Your email address is required but will not be published.




Comment