In response to jQuery .on() method - passing argument to event handler function two approaches are suggested:
Using javascript bind()
In a comment on the accepted answer Ignatio Segura suggests using javascript bind()
:
Actually, there is a neater syntax for that, using JS bind(): $(document).on('dblclick', '#an_tnam tr', ADS.bind(null, 'hello')); First parameter is the value you want "this" to have inside callback function. — Ignacio Segura Feb 19 2016 at 16:24
Using the data parameter in jQuery's on()
David Barker's answer suggests using the data
argument of jQuery's .on()
-method:
$(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);
});
which the handler can access via [event.data][6]
(as shown in the annoymous handler above).
Question
What are the differences between bind()
an the data
parameter to jQuery on()
?
When should I use which?