I have a nested-View setup which can get somewhat deep in my application. There are a bunch of ways I could think of initializing, rendering and appending the sub-views, but I'm wondering what common practice is.
Here are a couple I've thought of:
I have generally seen/used a couple of different solutions:
Solution 1
var OuterView = Backbone.View.extend({
initialize: function() {
this.inner = new InnerView();
},
render: function() {
this.$el.html(template); // or this.$el.empty() if you have no template
this.$el.append(this.inner.$el);
this.inner.render();
}
});
var InnerView = Backbone.View.extend({
render: function() {
this.$el.html(template);
this.delegateEvents();
}
});
This is similar to your first example, with a few changes:
render()
is called AFTER the inner view's element has been placed into the DOM, which is helpful if your inner view's render()
method is placing/sizing itself on the page based on other elements' position/size (which is a common use case, in my experience)Solution 2
var OuterView = Backbone.View.extend({
initialize: function() {
this.render();
},
render: function() {
this.$el.html(template); // or this.$el.empty() if you have no template
this.inner = new InnerView();
this.$el.append(this.inner.$el);
}
});
var InnerView = Backbone.View.extend({
initialize: function() {
this.render();
},
render: function() {
this.$el.html(template);
}
});
Solution 2 may look cleaner, but it has caused some strange things in my experience and has affected performance negatively.
I generally use Solution 1, for a couple of reasons:
render()
methodKeep in mind that if you are initializing a new View()
every time render()
is called, that initialization is going to call delegateEvents()
anyway. So that shouldn't necessarily be a "con", as you've expressed.