My JavaScript Module Pattern

/*! JavaScript Module Pattern by Taufik Nurrohman <https://github.com/tovic> */ (function($) { // module version $.version = '1.0.0'; // collect all instance(s) $.__instance__ = {}; // plug to all instance(s) $.each = function(fn, t) { return setTimeout(function() { var ins = $.__instance__, i; for (i in ins) { fn(ins[i], i, ins); } }, t === 0 ? 0 : (t || 1)), $; }; })(window.MyModule = function(target, config) { var $ = this; // access module instance from `this` scope with `this.MyModule` target.MyModule = $; // store module instance to `MyModule.__instance__` MyModule.__instance__[target.id || target.name || Object.keys(MyModule.__instance__).length] = $; // access module target with `$.target` $.target = target; // create some method(s) … $.set = function() { // ... return $; // make chainable … }; $.get = function() { // ... return $; // make chainable … }; $.reset = function() { // ... return $; // make chainable … }; // return the global object return $; });
I started to implement this pattern on all of my JavaScript project because this pattern allows me to add additional functionality without having to access the variable of the instance with this:

[js]
MyModule.each(function(a, b, c) {

// add `foo` method to all `MyModule` instances
a.foo = function() { … };

// a: refers to the instance object
// b: refers to the instance key in `MyModule.__instance__`
// c: refers to `MyModule.__instance__`
console.log(arguments);

});
[/js]

Inspired by that [`CKEDITOR.instances`]( http://ckeditor.com/forums/CKEditor-3.x/Getting-CKEDITOR-instance) object. By default, the instance scrapper will set a new item in `MyModule.__instance__` with a key generated by the target ID or target name or target index in the page.

[js]
var module = new MyModule(document.getElementById('foo'));

// chaining …
module.set().get().reset();

// access `MyModule` instance from `this` scope
module.target.addEventListener("click", function() {
console.log(this.MyModule);
}, false);

// test …
console.log(MyModule.__instance__);
console.log(MyModule.__instance__['foo'].target);
[/js]

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.