Skip to content

Instantly share code, notes, and snippets.

@ComFreek
Created September 29, 2012 19:38
Show Gist options
  • Save ComFreek/3805030 to your computer and use it in GitHub Desktop.
Save ComFreek/3805030 to your computer and use it in GitHub Desktop.
bindObjEvt(): wrap functions in order to use other contexts and additional arguments
/**
* Wraps a function. It enables passing a new context and new arguments.
* @param func The actual function
* @param obj The context ('this' object) to pass to 'func'. If null is given, 'func' gets the context forwarded.
* @param args The arguments 'func' should receive. These will be added to the list of already passed arguments.
* @param addCtx Specifies whether the originally passed context should be added as an argument.
* @return A wrapper function.
*
* @author ComFreek
* @license Public Domain. Attribution optional.
*/
function bindObjEvt(func, obj, args, addCtx) {
if (args === null) {
args = [];
}
return function () {
var newArgs = Array.prototype.slice.call(arguments).concat(args);
if (addCtx) {
newArgs.push(this);
}
func.apply(obj || this, newArgs);
};
}
var obj = {
initListeners: function () {
// #btn, #btn2, #btn3 are buttons.
document.getElementById("btn").addEventListener("click", bindObjEvt(this.clicked1, this));
document.getElementById("btn2").addEventListener("click", bindObjEvt(this.clicked2, this, ["Hello", "World!"]));
document.getElementById("btn3").addEventListener("click", bindObjEvt(this.clicked2, this, ["Hello", "World!"], true));
},
// this = obj
// evt = event object
clicked1: function (evt) {
},
// this = obj
// evt = event object
// var1 = Hello, var2 = World!
clicked2: function (evt, var1, var2) {
},
// this = obj
// evt = event object
// ctx = HTMLButtonElement object
clicked3: function (evt, ctx) {
}
};
// another example
var func = bindObjEvt(function () {
// convert arguments object to an array
var argumentsAsArray = Array.prototype.slice.call(arguments);
// will alert "C, D, B, A, [object Window]"
alert(argumentsAsArray);
},
document, ["A", "B"], true
);
func("C", "D");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment