Short answer:
Can trigger () pass data to your event handlers? Yes (as additional parameters)
Can trigger () pass data directly to event.data? 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 basic things.
- It creates a JQueryEventObject with the type and optional namespace that you give it.
- It sends or emits an event of a certain type, which moves through the DOM until it reaches the top or its propagation is stopped.
- It defines the signature of event handlers for this type of event.
- Function (event) {...} is the default value
- It passes the event as the first parameter to these handlers
- It (optionally) passes additional parameters to any event handlers
- function (event, optional Params) {}
Numbers 3 and 5 are the most important and important for you. Since you implicitly define api to handle this event, you want to be compatible with the way you fire events so that people who use your code can be compatible 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 a 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.
- .trigger (): emit an event and define parameters 2, 3, etc. sequentially if necessary
- .on (): event blocks dom. do some things, add or use event data, and use advanced options that trigger the addition or not.