Skip to content

Instantly share code, notes, and snippets.

@craigmaslowski
Forked from hxgdzyuyi/backbone-mixin.js
Last active May 15, 2017 05:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save craigmaslowski/5759511 to your computer and use it in GitHub Desktop.
Save craigmaslowski/5759511 to your computer and use it in GitHub Desktop.
Backbone.mixin = function (obj, mixin) {
var source = obj.prototype || obj;
if (!mixin)
throw new Error('Backbone.mixin: The mixin specified is undefined.');
// merge all properties in the mixin into the view's prototype
_.defaults(source, mixin);
// merge object literal properties (ensure's events, bindings, and channels)
_.each(['events', 'bindings', 'attributes', 'tagName'], function (key) {
if (mixin[key]) {
if (source[key]) {
_.defaults(source[key], mixin[key]);
} else {
source[key] = mixin[key];
}
}
});
// setup render chain
if (mixin.render) {
var oldRender = source.render;
source.render = function () {
mixin.render.apply(this, arguments);
var retVal = oldRender.apply(this, arguments);
if (retVal) {
return retVal;
}
return this;
};
}
// setup initialize chain
if (mixin.initialize) {
var oldInitialize = source.initialize;
source.initialize = function () {
mixin.initialize.apply(this, arguments);
oldInitialize.apply(this, arguments);
};
}
// setup remove chain
if (mixin.remove) {
var oldRemove = source.remove;
source.remove = function () {
mixin.remove.apply(this, arguments);
oldRemove.apply(this, arguments);
};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment