Skip to content

Instantly share code, notes, and snippets.

@scttnlsn
Created May 8, 2012 17:00
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scttnlsn/2637323 to your computer and use it in GitHub Desktop.
Save scttnlsn/2637323 to your computer and use it in GitHub Desktop.
Backbone.js base view
var BaseView = Backbone.View.extend({
close: function() {
this.closeSubviews();
this.unbindFromAll();
this.off();
this.remove();
if (this.onClose) this.onClose();
},
// Events
bindTo: function(object, e, callback, context) {
context || (context = this);
object.on(e, callback, context);
this.bindings || (this.bindings = []);
this.bindings.push({ object: object, event: e, callback: callback });
},
unbindFromAll: function() {
var self = this;
_.each(this.bindings, function(binding) {
binding.object.off(binding.event, binding.callback, self);
});
},
// Subviews
eachSubview: function(iterator) {
_.each(this.subviews, iterator);
},
appendSubview: function(view, el) {
el || (el = this.$el);
this.subviews || (this.subviews = {});
this.subviews[view.cid] = view;
el.append(view.el);
},
closeSubviews: function() {
this.eachSubview(function(subview) {
subview.close();
});
this.subviews = {};
},
detachSubview: function(view) {
if (this.subviews) {
delete this.subviews[view.cid];
}
view.$el.detach();
},
// Templates
templateContext: function() {
return {};
},
layout: function(context, template) {
this.closeSubviews();
this.$el.empty();
template || (template = this.template);
if (template) {
context || (context = this.templateContext());
this.$el.append(template(context));
}
},
render: function() {
this.layout();
if (this.onRender) this.onRender();
return this;
}
});
@alexbeletsky
Copy link

Great! I'll be using that in my application :)

@Kerry350
Copy link

Thanks for this, I'm using a lot of the ideas here in my own BaseView now :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment