Skip to content

Instantly share code, notes, and snippets.

@jgable
Created October 5, 2012 15:45
Show Gist options
  • Save jgable/3840613 to your computer and use it in GitHub Desktop.
Save jgable/3840613 to your computer and use it in GitHub Desktop.
Backbone Disposable and SubViews
DisposableView = Backbone.View.extend({
modelUnbindAll: function() {
var modelOrCollection = this.model || this.collection;
if (modelOrCollection) {
modelOrCollection.off(null, null, this);
}
},
disposed: false,
dispose: function() {
var properties,
self = this;
this.undelegateEvents();
this.modelUnbindAll();
this.off();
this.$el && this.$el.remove();
properties = [
'el', '$el',
'options', 'model', 'collection',
'subviews', 'subviewsByName',
'_callbacks'
];
_.forEach(properties, function(prop) {
self[prop] && delete self[prop];
});
if (typeof Object.freeze === "function") {
// You're frozen when your heart's not open.
Object.freeze(this);
}
}
});
SubViewableView = DisposableView.extend({
subviews: [],
subviewsByName: {},
// Add a subview with the given name
subview: function(name, view) {
if (name && view) {
this.removeSubview(name);
this.subviews.push(name);
this.subviewsByName[name] = view;
} else if (name) {
return this.subviewsByName[name];
}
},
// Remove a given subview if present.
removeSubview: function(nameOrView) {
if(!nameOrView) {
return;
}
var name, view, found,
self = this;
if (typeof nameOrView === "string") {
name = nameOrView;
view = this.subviewsByName[name];
} else {
view = nameOrView;
for (var key in p) {
if (!p.hasOwnProperty(key)) { continue; }
if (this.subviewsByName[key] === view) {
name = key;
break;
}
}
name = found;
}
},
dispose: function() {
// Dispose our sub views
_.forEach(this.subviews, function(subview) {
if (typeof subview.dispose === 'function') {
subview.dispose();
}
});
// Call the super to dispose us
DisposableView.prototype.dispose.call(this);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment