Skip to content

Instantly share code, notes, and snippets.

@mkuklis
Created April 10, 2012 01:48
Show Gist options
  • Save mkuklis/2347864 to your computer and use it in GitHub Desktop.
Save mkuklis/2347864 to your computer and use it in GitHub Desktop.
exploring different plugin initialization options
// version 1
function A() {
this.init();
}
A.prototype = {
init: function () {
A.inits.forEach(function (item) {
item.call(this);
}, this);
}
}
A.inits = [];
// plugin 1
A.inits.push(function () {
console.log("plugin 1");
});
// plugin 2
A.inits.push(function () {
console.log("plugin 2");
});
var a = new A();
// version 2
function A() {
A.ready.call(this);
}
A.ready = function (fn) {
if (fn) {
A.inits = A.inits || [];
A.inits.push(fn);
}
else {
A.inits && A.inits.forEach(function (item) {
item.call(this);
}, this);
}
}
// plugin 1
A.ready(function () {
console.log("init plugin 1");
});
// plugin 2
B.ready(function () {
console.log("init plugin 2");
});
// more generic ready
var ready = function (fn) {
if (fn) {
this.inits = this.inits || [];
this.inits.push(fn);
}
else {
var ctr = this.constructor;
ctr.inits && ctr.inits.forEach(function (fnc) {
fnc.call(this);
}, this);
}
}
function A() {
ready.call(this);
}
function B() {
ready.call(this);
}
​// plugin
ready.call(A, function () {
// init plugin stuff
});
ready.call(B, function () {
// init plugin stuff
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment