Skip to content

Instantly share code, notes, and snippets.

@mklabs
Created March 3, 2011 23:27
Show Gist options
  • Save mklabs/853849 to your computer and use it in GitHub Desktop.
Save mklabs/853849 to your computer and use it in GitHub Desktop.
My pretty bridge - inspired by, based on http://alexsexton.com/?p=51 - Using Inheritance Patterns to Organize Large jQuery Applications
// inspired by, based on http://alexsexton.com/?p=51
(function($, global) {
// Make sure Object.create is available in the browser (for our prototypal inheritance)
(function() {
if(typeof Object.create === 'function') {
return;
}
function F(){};
Object.create = function(o) {
F.prototype = o;
return new F();
};
})();
/**
* Bridge Utility method. Adds a new function to the jQuery prototype (a new plugin)
* which provides a clear way to bind application code to DOM elements.
*
* @method bridge
* @param name {String} simply the name of the jQuery method helper we want to create
* @param object {Object|Function} either an object or a function (module pattern, must return a public api).
* @namespace $
*/
$.bridge = function(name, object) {
var isFunction = $.isFunction(object);
$.fn[name] = function(options) {
if(!this.length) {
// Don't act on absent element - learned from 10 things I learned (Paul Irish)
return this;
}
return this.each(function() {
// Create our object (instance)
var obj = Object.create(isFunction ? object() : object),
setup = $.isFunction(obj.setup), init = $.isFunction(obj.init);
if(!setup || !init) {
// Bridge interface is not followed, warn user and return
console.warn('Bridge interface is not followed for ' + name + ' bridge.');
return;
}
// Init constructor function, this stands for the DOM element to apply logic to
obj.setup(options, this, name);
obj.init(options, this);
// Then, store our newly created instance in the DOM element data-store
$.data(this, name, obj);
});
};
};
})(this.jQuery, this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment