I have Backbone view that has sub-views and each of the could stay "active" (just click
or contextmenu
). And I need to get view reference to that active sub-view from parent view. What is the correct way to do it?
My view hierarchy looks like the following:
var OuterView = Backbone.View.extend({
initialize: function() {
this.children = {};
this.child = new Backbone.View();
this.children[this.child.cid] = this.child;
},
render: function() {
this.$el.html('<div data-view-cid="' + this.child.cid + '"></div>');
_.each(this.children, function(view, cid) {
this.$('[data-view-cid="' + cid + '"]').replaceWith(view.el);
}, this);
}
};
The approach I prefer is not to have active and inactive views, but to only render the view that is active, and to remove them when not needed.
In other words, the easiest way to handle state is to make things stateless.