I’m trying to learn Backbone from someone else’s Backbone app in combination with the documentation. There are two things I don’t understand about it that I can’t figure out from the documentation. Hope someone might be able to explain…
Gist of the app
It’s an app where you can drag and drop company names into boxes.
The app has a Company View, a Company Model and a Companies Collection.
It also has a Bucket View, a Bucket Model, and Buckets Collection
It also has a general App View that’s not associated with any model.
Problems…
First- Is it weird that a view would never be rendered?
The App View is instantiated like this
window.App = new AppView();
and it gets different things going in the app (populating the buckets with company names etc and setting up some events). However, the App View is never rendered. The Bucket View and the Company View, on the other hand, are both rendered at different points in the code. For example,
var view = new BucketView({model: bucket});
this.$("#bucket-list").append(view.render().el);
But never that App View. This App View also has no render function. So is it weird that it has a View that’s never rendered? Should its code be somewhere else?
Second Considering that App view is never rendered, is there any reason why they would have to change the default setting of el to the name of the main container div in the layout? For example, in the App view, they do this…
el: $("#mainapp"),
However, if this view’s never rendered, is there any reason to change the default setting of el?
When you create a Backbone.View instance normally, it will immediately generat an
elon the view for you. This is used as the placeholder for all of the HTML that the view will manage, and you generally populate the view’selwith your HTML in the render method, as you’ve already noted.In some cases, though, you don’t want to render a completely new set of HTML elements. Instead, you’ll want to manage some existing HTML that’s already part of the DOM. In this case, you can easily attach a backbone view to the existing DOM element by specifying the
elin the constructor, as you’ve shown with theel: $("#mainapp")line.When a Backbone view sees that it already has an
el, it does not generate it’s own. Instead, it uses what it was handed.So, to directly answer your two questions:
1) First- Is it weird that a view would never be rendered?
No, because …
2) if this view’s never rendered, is there any reason to change the default setting of el?
The question is slightly off in a manner that that can’t be directly answered. In reality, the view is never rendered because they are setting the
elin the call to the constructor.