I have the following script which does not work
As Anthony Grist pointed out, the .on()
method is expecting a function reference at that part; you're evaluating a function which returns nothing (null
).
However, one fun feature of JavaScript is that everything is an object, including functions. With a small modification, you can change ADS()
to return an anonymous function object instead:
function ADS(e){
return function(){ alert(e); };
}
http://jsfiddle.net/cSbWb/
The .on()
function expects a function reference to be passed; what you're doing is calling the function and passing its return value. If you need to pass a parameter you'll need to wrap the call in an anonymous function.
$(document).on('dblclick', '#an_tnam tr', function(event) {
ADS('hello');
});
jQuery always passes its normalized event object as the first argument to the function to be executed.
function ADS(e){ alert(e); }
$(document).ready(function(){
$(document).on("dblclick","#an_tnam tr", function (e) { ADS('hello') });
});
will do the trick.
You can pass extra data to an event handling function and can be accessed using event.data
within the handler.
$(document).on('dblclick', '#an_tnam tr', { extra : 'random string' }, function(event)
{
var data = event.data;
// Prints 'random string' to the console
console.log(data.extra);
}
You can also send extra data to any event you like when triggering the event from an external source using the .trigger()
method
$('#an_tnam tr').trigger('click', [{ extra : 'random string' }]);
The difference with passing data to the trigger method is that it expects the handler to take extra arguments of the length of the array passed in. The above would expect the handler to have one extra argument to contain the object passed in.
$('#an_tnam tr').on('click', function(event, obj)
{
// Prints 'random string' to the console
console.log(obj.extra);
}
Actually, there is a very neat simple way to achieve this, with no extra clutter and no anonymous functions, using JS bind():
$(document).on('dblclick', ADS.bind(null, 'hello'));
First parameter is the value you want "this" to have inside callback function.
MOre info in Mozilla Developer Network: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_objects/Function/bind
function ADS(e) {
return function() {
alert(e);
};
}
Like that when you're doing
$(document).on("dblclick","#an_tnam tr", ADS('hello'));
, it is the returned function that is assigned as event handler (and your string argument is passed when you're assigning the handler, not when it's called).