Search code examples
javascriptbackbone.jszepto

What are el and $el in backbone's view?


I'm trying to avoid wrapping with empty div when render view in backbone. I do it with the following code

this.$el.replaceWith(this.template(this.model.attributes));
return this;

but I get empty div when I append this view by

$("#product-pannel").append(productsView.render().el);

someone give the solution like this

render: function(){
    var html = this.template(this.model.toJSON()));
    var newElement = $(html)
    this.$el.replaceWith(newElement);
    this.setElement(newElement);
    return this;
}

but I can't understand why should I do this so complicatedly above can someone tell me the mystery of el an $el?


Solution

  • el points to the the view element (the one that holds rest of template) and $el is a jQuery object represeting el element So that you don't have to do $(this.el) all the time.

    This is clearly mentioned in the documentation.

    You can either specify an existing DOM element as the view element using el option, or backbone creates a DOM element for every view. By default this will be a <div>. If you don't want an empty <div>, customize the element backbone creates as the top level element of your view template using options like tagName, attributes etc.

    setElement is for dynamically changing the view element to something else... I've rarely (or never) seen it actually being used.