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.
We can consider a scenario where you have the following div in the DOM
This div can be any other element where you wanted to insert the html generated by your view.
Suppose, you have following template,
You can specify
existingas anelfor the view as its already present in the div. The only problem you will have is, if its some tag likebodyor 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
existingasel, render view’s html in thateland after that callsetElementright after appending the template html to the DOM like,What this will do is, it will change the
elfor the view fromexisting(or any other DOM element) toinside_template. So while removing theel,inside_templateelement will be removed, keepingexistingelement as it is in the DOM.