Friday, July 4, 2014

Ensure Backbone View Is In The DOM

A nice aspect of Backbone views is that they're guaranteed to have an element. This takes place before the view constructor is called. Even if you don't supply any element details, such as the tag name, the element id — there will always be a div element. However, one thing you have to always remember is the add the element to the DOM. While the view ensures the element gets created, it doesn't ensure that the element is attached to the DOM. This is actually a good thing, because you don't always want to be forced to be working on an element that's in the DOM.

But, sometimes, it's handy to be able to just add the element to the DOM. That way, it gets inserted as part of the view creating process and doesn't require an extra step. Less chance for weird errors that arise from the element not being in the DOM when it's supposed to be. Here's an example that shows you how to override the _ensureElement() view method. Note that this is a private method, and doesn't need to be invoked manually — it's called for us, before the view constructor.

new (Backbone.View.extend({
    parent: 'body',
    _ensureElement: function() {
        Backbone.View.prototype
            ._ensureElement.call( this );
        if ( this.parent ) {
            this.$el.appendTo(
                $( this.parent ) );    
        }
    }
}))();

We've added a new option to the view here called parent. This is either a jQuery object or an element, or a selector. Standard stuff. We check for this option in our implementation of _ensureElement(). If parent is there, we append the created element to it.

No comments :

Post a Comment