jQuery - the trigger method with multiple arguments
Posted: 20 Jan 2015, 11:21
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:
And the result:
But with a single argument (the obj) it works.
This code works:
Displays this alert
- With one argument it works but with 2 arguments it results "undefined".
So, how to pass two additional arguments in 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>
Code: Select all
ID: dv1
undefined
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);
});
Code: Select all
ID: dv1
prop2
So, how to pass two additional arguments in the trigger() method?