As Andreas points out in a comment, there's a solution to this that's specific to jQuery event handlers: The data
argument to the on
function.
More generally, though, what you're looking for is sometimes called "currying" (or "partial application;" purists tell me one of them is technically incorrect but I can never remember which).
I have a function I use for that which I add to Function.prototype
; it looks like this (see comments):
(function() {
var slice = Array.prototype.slice;
Object.defineProperty(Function.prototype, "curry", {
value: function() {
// Remember the original function and the arguments we wre called with
var f = this,
curried = slice.call(arguments);
// Return a new function
return function() {
// Our function was called, add in any arguments it was called with...
var args = curried.concat(slice.call(arguments));
// ...and call the original, passing along `this`
return f.apply(this, args);
};
}
});
})();
In your case, you'd use it like this:
var label = 'Added';
$('#myDiv').append($('<button type="button">Add</button>').click(add.curry(label)));
Note that your add
function will be called with the value of label
(as it was when we made the curry
call, not as it is later), followed by any arguments that the curried function was called with (e.g., the event object).
Example:
(function() {
var slice = Array.prototype.slice;
Object.defineProperty(Function.prototype, "curry", {
value: function() {
// Remember the original function and the arguments we wre called with
var f = this,
curried = slice.call(arguments);
// Return a new function
return function() {
// Our function was called, add in any arguments it was called with...
var args = curried.concat(slice.call(arguments));
// ...and call the original, passing along `this`
return f.apply(this, args);
};
}
});
})();
function add(text) {
console.log("add called with text = '" + text + "'");
}
var label = 'Added';
$('#myDiv').append($('<button type="button">Add</button>').click(add.curry(label)));
<div id="myDiv"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>