jQuery - the trigger method with multiple arguments

Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
PloMar
Posts: 48

jQuery - the trigger method with multiple arguments

I'm playing with jQuery. Now I test the trigger() method.
I try to trigger a custom method and pass two additional arguments (an object and a string), but it doesn't work.
When I click on #btn, the "custom" event is triggered, and is called a function wich has 3 parameters: the event, an object, and a string. The function should display an alert with the ID of a Div and the property from the object passed as argument.
This is the code:

Code: Select all

<div id="dv1">div</div>
<button id="btn">Click</button>
<script>
// register a custom event
$('#dv1').on('custom', function(event, obj, prop) {
  alert('ID:'+ event.target.id +'\n'+ obj[prop]);
});
$('#btn').on('click', function() {
  var obj = {p1: 1, p2: 'prop2'};

  // here trigger the 'custom' method, passing 2 additional arguments (obj and 'p2')
  $('#dv1').trigger('custom', obj, 'p2');
});
</script>
And the result:

Code: Select all

ID: dv1
undefined
But with a single argument (the obj) it works.
This code works:

Code: Select all

// register custom event
$('#dv1').on('custom', function(event, obj) {
  alert('ID:'+ event.target.id +'\n'+ obj['p2']);
});
$('#btn').on('click', function() {
  var obj = {p1: 1, p2: 'prop2'};

  // here trigger the 'custom' method, passing obj
  $('#dv1').trigger('custom', obj);
});
Displays this alert

Code: Select all

ID: dv1
prop2
- With one argument it works but with 2 arguments it results "undefined".
So, how to pass two additional arguments in the trigger() method?

Admin
When you pass multiple arguments with trigger(), and those arguments aren't a number or a string, you should pass all the additional arguments into an array.
This example works:

Code: Select all

<div id="dv1">When click on the button will trigger the 'custom' event. It displays an alert with the ID of this Div and a property of an object passed as arguments.</div>
<button id="btn">Click</button>
<script>
// register a custom event
$('#dv1').on('custom', function(event, obj, prop) {
  alert('ID:'+ event.target.id +'\n'+ obj[prop]);
});
$('#btn').on('click', function() {
  var obj = {p1: 1, p2: 'prop2'};

  // here trigger the 'custom' method, passing 2 additional arguments into an array [obj, 'p2']
  $('#dv1').trigger('custom', [obj, 'p2']);
});
</script>
Demo:
When click on the button will trigger the 'custom' event. It displays an alert with the ID of this Div and a property of an object passed as arguments.

Similar Topics