Skip to content

Instantly share code, notes, and snippets.

@jferris
Created April 29, 2011 15:58
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jferris/948520 to your computer and use it in GitHub Desktop.
Save jferris/948520 to your computer and use it in GitHub Desktop.
Cleaning up views as you leave them in Backbone
CompositeView = function(options) {
this.children = [];
Backbone.View.apply(this, [options]);
};
_.extend(CompositeView.prototype, Backbone.View.prototype, {
leave: function() {
this.unbind();
this.remove();
_(this.children).invoke("leave");
},
renderChild: function(view) {
view.render();
this.children.push(view);
}
});
CompositeView.extend = Backbone.View.extend;
ExampleController = SwappingController.extend({
routes: {
"one" : "one",
"two" : "two"
}
one: function() {
this.swap(new OneView());
},
two: function() {
this.swap(new TwoView());
}
});
OneView = CompositeView.extend({
render: function() {
var childView = new ChildView();
this.renderChild(childView);
$(this.el).append(childView);
}
});
SwappingController = function(options) {
Backbone.Controller.apply(this, [options]);
};
_.extend(SwappingController.prototype, Backbone.Controller.prototype, {
swap: function(newView) {
if (this.currentView && this.currentView.leave)
this.currentView.leave();
this.currentView = newView;
this.currentView.render();
$(this.el).empty().append(this.currentView.el);
}
});
SwappingController.extend = Backbone.Controller.extend;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment