Can you set event.data with jquery trigger

Jquery

Jquery Problem Overview


With jQuery .on() you can pass an optional parameter to set the event data. Can you do this with trigger as well?

Jquery Solutions


Solution 1 - Jquery

#Short Answer: Can trigger() pass data to your event handlers? Yes (as additional parameters)

Can trigger() pass data into the event.data object directly? No (only on() does this)

// Using this will pass myData to every event handler as the second parameter. 
trigger('myEvent', [myData]) 
// Instead of this
on('myEvent', function(evt) {...});
// You would do this
on('myEvent', function(evt, myData) {...});

#Long Answer

The trigger() method does 5 main things.

  1. It creates a JQueryEventObject with the type and optional namespace you give it
  2. It sends or emits an event of a specific type that travels up the DOM until it reaches the top or its propagation is stopped.
  3. It defines the signature of event handlers for that type of event.
    • function(event) {...} is the default
  4. It passes the event as the first parameter to those handlers
  5. It (optionally) passes additional parameters to any handlers of the event
    • function(event, additionalParams) {}

Numbers 3 and 5 are most important and relevant to you. Since you implicitly define the api for handling this event, you want to be consistent with how you trigger events so that people who use your code can be consistent with how they use it.

Example 1 Consistency

function Car(speed, tires, brakes) {
    this.speed = speed;
    this.tires = tires;
    this.brakes = brakes;
}

Car.prototype.brake = function(amount) {
    // You can do this (Event handler will have access to these parameters)
    car.trigger('brake.car', [this.speed, this.brakes, this.tires, amount])
    // Or this (Event handler will have access to these parameters)
    car.trigger('brake.car', [this, amount])
    // but try not to mix and match with the same event type
}
...
//This is the first way from above (choose one or the other, but don't mix and match).
passenger.on('brake.car', {person: passenger}, function(evt, carSpeed, carBrakes, carTires, brakeAmount){
    if(brakeAmount > 50)
        passenger.hangOnTight();
    }
})

...
// This is the second way from above (choose one or the other, but don't mix and match).
passenger.on('brake.car', function(evt, car, brakeAmount){
    if(brakeAmount > 50)
        passenger.hangOnTight();
    }
})

Example 2 Here is the typical example showing both trigger() and on():

jQuery(document).on('eventName' {eventData1: 'foo', eventData2: 'bar'}, function (evt, extraParam1, extraParam2) {
    //This code runs when the event is triggered
    console.log(evt.data.eventData1) // foo
    console.log(evt.data.eventData2) // bar
    console.log(extraParam1) // 'extra param 1'
    console.log(extraParam2) // 'extra param 2'
});

jQuery(document).trigger('eventName', ['extra param 1', 'extra param 2']);

So just remember.

Solution 2 - Jquery

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).

Solution 3 - Jquery

You can do this way:-

Example

  //Create a new jQuery.Event object without the "new" operator.
  var e = jQuery.Event("click");

  // trigger an artificial click event
  jQuery("body").trigger( e );

You can pass event.data too with the same approach. Refer this Event Object

Solution 4 - Jquery

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 });

Solution 5 - Jquery

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

Solution 6 - Jquery

Yes. The documentation says:

> .trigger( eventType [, extraParameters] ) > > Note the difference between the extra parameters we're passing here and the eventData parameter to the .bind() method. Both are mechanisms for passing information to an event handler, but the extraParameters argument to .trigger() allows information to be determined at the time the event is triggered, while the eventData argument to .bind() requires the information to be already computed at the time the handler is bound.

Solution 7 - Jquery

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]);

Solution 8 - Jquery

As far as I know, the same dataObject that you defined with the original :

$('selector').on('eventName', dataObject , functionName)

will be also sent when you use `$('selector').trigger('eventName').

you can also pass parameters (like other mentions in their answers) but those parameters will be additional arguments (you will still have the dataObject you set in the .on() function).

Solution 9 - Jquery

It took me a while to understand the philosophy behind this. An event involves two entities: listener and dispatcher. The event.data field was intended to be used by the listener only. It's sort of like assigning a name to a phone number:

$("(818)548-2733").on("incomingcall", null, "Mom", pickup);

You could pick up the phone and wait for the other side to tell you that she is your Mom. Or you can use event.data to attach the extra information relevant to this event.

The $.trigger and $.triggerHandler methods are called by the dispatcher side of an event. That's why they don't let you specify the event.data. Instead, you can use their extraParameters argument.

Solution 10 - Jquery

$("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");

Solution 11 - Jquery

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);
    });

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question9-bitsView Question on Stackoverflow
Solution 1 - JqueryTxRegexView Answer on Stackoverflow
Solution 2 - JqueryHartiView Answer on Stackoverflow
Solution 3 - JquerySiva CharanView Answer on Stackoverflow
Solution 4 - JqueryDavidView Answer on Stackoverflow
Solution 5 - JqueryStarxView Answer on Stackoverflow
Solution 6 - JquerybububabaView Answer on Stackoverflow
Solution 7 - JqueryRafael VergerView Answer on Stackoverflow
Solution 8 - Jqueryyoav barneaView Answer on Stackoverflow
Solution 9 - JquerySarsaparillaView Answer on Stackoverflow
Solution 10 - JqueryLord NightonView Answer on Stackoverflow
Solution 11 - JqueryTung XenView Answer on Stackoverflow