I'm confused about the meaning of el
in Backbone views. Some tutorials (such as this one) make it seem like el
is the parent of the view being created, where the render
method is supposed to append the view to its el
. Others (like this) treat it like it's the element of the view itself. Is there a best practice concerning this?
el
is definitely the element the view corresponds to, not its parent. In your first example, they considering the whole page body
to be the view, and then upon rendering, they insert the components that compose it. I suppose this might be appropriate for top-level views representing entire pages. Backbone gives you a lot of flexibility (i.e. rope to hang yourself with), so you can do things in many ways. Generally speaking, however you do it, it works best if you actually construct and append the components of your view before attaching it to the DOM wheverer possible. This is mentioned in your second example, and in the Backbone docs themselves:
All views have a DOM element at all times (the el property), whether they've already been inserted into the page or not. In this fashion, views can be rendered at any time, and inserted into the DOM all at once, in order to get high-performance UI rendering with as few reflows and repaints as possible.
Projects like Marionette implement a lot of Backbone best practices and let you operate at a higher level of abstraction. I highly recommend checking it out, instead of trying to figure out all the best-practice patterns yourself.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments