It was thinking about this situation that was added between the parameters of .on
the possibility to pass arbitrary data to the Handler. Any object passed as a parameter just before the Handler will be available within it through event.data
. Example:
function retornaNada(evento) {
var data = evento.data;
console.log(data.foo); // Imprime "bar"
}
$("a").on("click", { foo:"bar" }, retornaNada);
Several other jQuery methods accept this parameter data
. In the case of "on", the general form (according to the documentation) is:
.on( events [, selector ] [, data ], Handler(eventObject) )
If this is not enough for you (e.g., you already have a function ready, and want to use it without modification as Handler event), then it is necessary to transform it through the operation of currying. There are several ways to do this:
currying "manual":
$("a").on("click", function(e) { retornaNada(10); });
jQuery.proxy
:
$("a").on("click", jQuery.proxy(retornaNada, meuThis, 10));
Function that returns function:
function tranforma(parametro) {
return function(evento) {
retornaNada(parametro);
}
}
$("a").on("click", transforma(10));
or more generic:
function tranforma(fn, meuThis, parametro) {
return function(evento) {
fn.call(meuThis, parametro);
}
}
$("a").on("click", transforma(retornaNada, meuThis, 10));
or even more generic (reaching a point that is almost identical to the jQuery.proxy
):
function tranforma(fn, meuThis) {
var args = Array.prototype.slice.call(arguments, 2, arguments.length);
return function(evento) {
fn.apply(meuThis, args);
}
}
$("a").on("click", transforma(retornaNada, meuThis, 10));
Update: on the use of this
Both in the case of jQuery.proxy
how much in my job transforma
(in the most generic forms), a parameter meuThis
is expected. This is because every function invocation in Javascript expects a Binding for the keyword this
, even when the function is not being called in the content of an object (i.e. it is not a method). Example:
console.log(this); // Vai imprimir o "objeto global" (no caso de um browser, "window")
function a() {
console.log(this);
}
a(); // também imprime o objeto global
var obj = { x:a };
obj.x(); // Vai imprimir "obj"
obj.criaLinks = function() {
$("a").on("click", jQuery.proxy(retornaNada, this, 10));
// Como se fosse: obj.retornaNada(10)
$("a").on("click", jQuery.proxy(retornaNada, window, 10));
// Como se fosse: window.retornaNada(10)
$("a").on("click", jQuery.proxy(retornaNada, { foo:"bar" }, 10));
// Como se fosse: { foo:"bar" }.retornaNada(10)
};
obj.criaLinks();
Normally "Call-by-reference" has a slightly different meaning than the one you are using.
– hugomg