Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery .on() method - passing argument to event handler function

I have the following script which does not work

<script type="text/javascript" >

   function ADS(e){ alert(e); }

   $(document).ready(function(){
          $(document).on("dblclick","#an_tnam tr", ADS('hello'));
          $(document).on("dblclick","#kv_tnam tr", ADS('world'));
          // ....  
 });

</script>

how can I pass argument to event handler function ADS ?

like image 444
Paramore Avatar asked Apr 09 '13 14:04

Paramore


3 Answers

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 .on() expects the handler to take extra arguments of the length of the array passed in. The above would expect the handler to have (only) 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);
}
like image 191
David Barker Avatar answered Oct 11 '22 23:10

David Barker


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.

like image 44
Anthony Grist Avatar answered Oct 11 '22 23:10

Anthony Grist


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

like image 31
Ignacio Segura Avatar answered Oct 11 '22 23:10

Ignacio Segura