Skip to content

Instantly share code, notes, and snippets.

@tiste
Last active August 29, 2015 14:03
Show Gist options
  • Save tiste/40e89a239fb45fcde32b to your computer and use it in GitHub Desktop.
Save tiste/40e89a239fb45fcde32b to your computer and use it in GitHub Desktop.
How to create a javascript plugin w/ callbacks
function Module(foo, bar) {
this.foo = foo;
this.bar = bar;
}
Module.prototype.getData = function(fooFunc) {
if (!fooFunc || typeof fooFunc !== 'function')
return;
if (this.foo == '' || this.bar == '') {
fooFunc('Fields empty');
} else {
fooFunc(null, {foo: this.foo, bar: this.bar});
}
}
var obj = new Module('it', 'works');
obj.getData(function(err, data) {
if (err === null) {
console.log(data);
} else {
console.log(err);
}
});
/*******************
*******************
*******************/
Module.prototype.getData = function(fooFunc) {
if (this.foo == '' || this.bar == '') {
if (fooFunc && typeof fooFunc.error === 'function')
fooFunc.error.apply(this, ['No...']);
} else {
if (fooFunc && typeof fooFunc.success === 'function')
fooFunc.success.call(this, 'OKAY, ' + this.foo + ' ' + this.bar + '!');
}
}
obj.getData({
success: function(data) {
alert(data);
},
error: function(err) {
console.log(err);
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment