Search code examples
javascriptdombackbone.js

Backbone using el that is not yet created?


I'm building a single web page app using Backbone.

My master views depends on template that will replace the body part of my page based on the URL, but since I must provide an "el" for that view, I wanted it to be the template itself, that would be inserted in the DOM in the "render" or "initialize" method.

But when I call new MyMasterView, the el is undefined since it isn't present in the DOM at instantiation.

How can I do ?

The only fix I found is to set the el to the existing DOM where I replace the content, and call a .remove().append(the_template) in the render, but I'm not sure it's the best way.


Solution

  • We can consider a scenario where you have the following div in the DOM

    <div id="existing">
    
    </div>
    

    This div can be any other element where you wanted to insert the html generated by your view.

    Suppose, you have following template,

    <div id="inside_template">
      <!-- content of the template goes here -->
    </div>
    

    You can specify existing as an el for the view as its already present in the div. The only problem you will have is, if its some tag like body or something, then if you remove it from the view while clearing the view (to prevent memory leaks), it will delete the tag from the dom which might not be desired.

    A solution to that could be, specify existing as el, render view's html in that el and after that call setElement right after appending the template html to the DOM like,

    render : function() {
      this.$el.html(this.template());
      this.setElement("#inside_template");
    
      // another render method content
    }
    

    What this will do is, it will change the el for the view from existing (or any other DOM element) to inside_template. So while removing the el, inside_template element will be removed, keeping existing element as it is in the DOM.