With jQuery .on()
you can pass an optional parameter to set the event data. Can you do this with trigger as well?
This was the approach I took.
$('#foo').on('click', { init: false }, function(e, data) {
data = data || e.data;
console.log(data.init); // will be true in the trigger, and false in the click.
})
.trigger('click', { init: true });
$("pressedButton").on("click", function(event) {
var buttonID = $(this).data('buttonID');
alert(buttonID); // alerts 'save' string passed as an argument
});
$("pressedButton").data('buttonID','save').trigger("click");
you can do this way
<input id="btn" type="button" />
<input id="btn2" type="button" />
$("#btn").bind("click",function(e) {
var data2 = {type:"click",name:"Raptors",sport:"basketball"};
$("#btn2").trigger(data2);
});
$("#btn2").bind("click",function(e) {
console.log(e.name + " " + e.sport);
});
I know an workaround we can use for this
$("button").on("click", function(event) {
event.data = $(this).data('events'); // get the data value
alert(event.data); //use your data as you want
});
//Now set the data value and trigger
$("button").data('events','youreventsvalue').trigger("click");
Here is a demo
In jQuery site you can see the declaration for the trigger
function: .trigger( eventType [, extraParameters] )
The extraParameters
must be an array or a single object and you will be allowed to get these objects with arguments[1+] (arguments[0] is equal to event object).
So, here's an example:
$('#foo').bind('custom', function(event) {
if ( arguments.length > 1 ) {
$.each(arguments, function(i,arg){
alert("element " + i + " is " + arg);
})
}
});
$('#foo').trigger('custom', ['Custom', 'Event', { 'test' : 'attr from object' }, 123]);
I hope I didn't get you wrong but do you mean passing additional data with the trigger
method?
$(app.Model).trigger("foo", additionalData);
And somewhere else...
$(app.Model).on("foo", callback);
var callback = function(event, additionalData) {
console.log(additionalData);
}
Note that if you pass additional data with trigger
, your first parameter in the callback function always is the actual event you are triggering.
The app.Model
I used in the parenthesis is the object that should trigger an event and that also listens on that event. Think of it as kind of a namespace. You can always use document
, any DOM selector or even object you like, just make sure that both the trigger
and the on
must use the same object (that is, DOM elements that are removed from the DOM temporarily are error-prone).