Today I want to figure out what kind of events to use when one of my views is added to the DOM. This can have a lot of ramifications for positioning elements around the view and setting up properties on the view itself.
More searching reveals that almost everyone points to the livequery plugin for jQuery. Livequery seems like a mostly deprecated plugin since jQuery has both .live() and .delegate() methods now. The one exception is that livequery will fire a callback when an element is created.
Another alternative is to fire a custom event from my View’s render method. While this does seem cleaner than using a plugin unfortunately we might call render over and over again. A middle of the road solution would be to use .one() to bind to the first render event.
In my mind I would like every Backbone View to extend a base class which dispatches a custom addedToDOM event and removedFromDOM event. I’m not sure what the performance cost of using livequery to do this is but let’s write it up and maybe we can do a jsPerf later.
Load a jQuery plugin with AMD
Let’s download livequery from the git repo. Now that we have it we’re in another little dilemma. The boilerplate loads jQuery like an AMD module…so how do you use a jQuery plugin with AMD?
It’s very possible this is not the intended method but here’s how I’ve gone about solving the problem. Since require.js is only going to load stuff if we specify it as a dependency then we’ll need to request the plugin just like any other module. If we put the plugin in our assets/js/plugins folder then we’ll already have a path to plugins provided by config.js.
Then we can load livequery as if it were any other module. This might seem odd because a dependency gets passed to our pseudo-constructor as an argument:
But we’re not going to use that argument. It’s just there to make sure that jquery.livequery.js gets added to the page. We’ll ignore it and use livequery via jquery instead, like so:
Keep in mind that require.js and AMD are just tacking the script elements onto the page. Requiring our plugin in this fashion is no different than tacking a script onto the HTML at runtime.
Here’s my example.js file from the last post, now using livequery to listen for when the element is added to and removed from the DOM.
I tried this out by adding and removing the Example.Sections view from the DOM and both console logs fired, so yeah, awesome! In lieu of creating a base class and adding an addedToDOM and removedFromDOM event we can do something like this to achieve that effect: