Backbone, not “this.el” wrapping

You can take advantage of view.setElement to render a complete template and use it as the view element.

setElement view.setElement(element)
If you’d like to apply a Backbone view to a different DOM element, use setElement, which will
also create the cached $el reference and move the view’s delegated
events from the old element to the new one

Two points you have to account for:

  1. setElement calls undelegateEvents, taking care of the view events, but be careful to remove all other events you might have set yourself.
  2. setElement doesn’t inject the element into the DOM, you have to handle that yourself.

That said, your view could look like this

var FullTemplateView = Backbone.View.extend({

    render: function () {
        var html, $oldel = this.$el, $newel;

        html = /**however you build your html : by a template, hardcoded, ... **/;
        $newel = $(html);

        // rebind and replace the element in the view
        this.setElement($newel);

        // reinject the element in the DOM
        $oldel.replaceWith($newel);

        return this;
    }
});

And a working example to play with http://jsfiddle.net/gNBLV/7/

Leave a Comment