Created
August 1, 2012 05:11
-
-
Save keelii/3223885 to your computer and use it in GitHub Desktop.
The Best jQuery Plugin Design Pattern ...
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*! | |
* from: http://stackoverflow.com/questions/7127600/which-jquery-plugin-design-pattern-should-i-use | |
*/ | |
(function ($) { | |
// the constructor | |
var MyClass = function (node, options) { | |
// node is the target | |
this.node = node; | |
// options is the options passed from jQuery | |
this.options = $.extend({ | |
// default options here | |
id: 0 | |
}, options); | |
}; | |
// A singleton for private stuff | |
var Private = { | |
increaseId: function (val) { | |
// private method, no access to instance | |
// use a bridge or bring it as an argument | |
this.options.id += val; | |
} | |
}; | |
// public methods | |
MyClass.prototype = { | |
// bring back constructor | |
constructor: MyClass, | |
// not necessary, just my preference. | |
// a simple bridge to the Private singleton | |
Private: function ( /* fn, arguments */ ) { | |
var args = Array.prototype.slice.call(arguments), | |
fn = args.shift(); | |
if (typeof Private[fn] == 'function') { | |
Private[fn].apply(this, args); | |
} | |
}, | |
// public method, access to instance via this | |
increaseId: function (val) { | |
alert(this.options.id); | |
// call a private method via the bridge | |
this.Private('increaseId', val); | |
alert(this.options.id); | |
// return the instance for class chaining | |
return this; | |
}, | |
// another public method that adds a class to the node | |
applyIdAsClass: function () { | |
this.node.className = 'id' + this.options.id; | |
return this; | |
} | |
}; | |
// the jQuery prototype | |
$.fn.myClass = function (options) { | |
// loop though elements and return the jQuery instance | |
return this.each(function () { | |
// initialize and insert instance into $.data | |
$(this).data('myclass', new MyClass(this, options)); | |
}); | |
}; | |
}(jQuery)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment