I am using custom events to broadcast navigation messages (between related plugins).
The simple trigger code currently looks like this:
$button.trigger('navigate', { url: link, target: target });
The receiving code looks like:
$element.on('navigate', function (e, params)
{
e.preventDefault();
e.stopPropagation();
// Do something custom here with params.url and params.target
});
The problem is I also need to test isDefaultPrevented()
on the event object that was sent to trigger
.
I can create a custom event object and test it with:
var eo = $.Event('navigate');
$button.trigger(eo);
if (!eo.isDefaultPrevented())
{
// Do the default actions
}
But jQuery's trigger()
does not have a version that takes both a JQueryEventObject
and parameters and I can't figure out how to pass the parameters through with the trigger.
Note: I do not want to use the e.data
property as loads of existing code expects the params object to be provided as the second parameter to any event handlers. I would prefer something that worked like this:
var eo = $.Event('navigate');
$button.trigger(eo, { url: link, target: target });
Q: How do you use a custom JQueryEventObject
and pass parameters to trigger
?
Note: I am using TypeScript, so I am going by what the jQuery definitions file says is available.
This is not documented, but jQuery trigger() actually does support what I was trying to do (pass an event object and parameters).
The relevant jQuery code looks like this (only one method, so the second parameter were just treated as optional and the first parameter can be a string
or an JQueryEventObject
):
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
My problem lay with trusting the documentation and the TypeScript definition file for Jquery (ie.. jQuery.d.ts) which only has these entries:
trigger(eventType: string, ...extraParameters: any[]): JQuery;
trigger(event: JQueryEventObject): JQuery;
behind the scenes however I found you can actually pass:
trigger(event: JQueryEventObject, extraParameters: any[]): JQuery;
Option 1:
The TypeScript
solution is to either cast the element to any (which is bad) e.g.:
(<any>element).trigger(eo, {url: link, target: target});
or to add a new TypeScript
definition for JQuery to allow for the extra parameters:
Option 2: (best answer)
// Declare our additions to JQuery object
interface JQuery
{
trigger(event: JQueryEventObject, ...extraParameters: any[]): JQuery;
}
I traced into Jquery using the first option, then went with the second option.