Last active
August 29, 2015 14:03
-
-
Save tiste/40e89a239fb45fcde32b to your computer and use it in GitHub Desktop.
How to create a javascript plugin w/ callbacks
This file contains hidden or 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
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