Skip to content Skip to sidebar Skip to footer

How To Send Trigger Event And Know If It Was Cancelled/consumed By Any Recipient?

I am building a custom navigation system, where the anchor links are store in parent items as data-url = attributes. This way the entire item is clickable (among other features). I

Solution 1:

Documentation... Argh!

It actually turns out to be reasonably simple but is only mentioned on this page http://api.jquery.com/category/events/event-object/ and not on trigger reference page:

"Create an event object yourself and pass it to trigger!" :)

var e = jQuery.Event( "navigate" );
$this.trigger(e, [$this.attr('data-url'), $this.attr('data-target')]);

if (e.isDefaultPrevented()) {
    // Someone prevented the default event!
    alert('Prevented!');
}
else
{
    alert('Navigated!');
    // Navigate like normal link
    //window.location = $this.attr('data-url');
}

Improved version:

You can also simply extend the jQuery event object (instead of passing parameters).

var e = jQuery.Event( "navigate", {url: $this.attr('data-url'), navtarget: $this.attr('data-target')} );
$this.trigger(e);

and reference custom event parameters instead:

$(document).on('navigate', function (e) {
    alert(" url='" + e.url + "' target= \'" + e.navtarget + "'");
    // Process .content targetted links here and not at source
    if (e.navtarget == '.content') {
        e.preventDefault(); // or something else?
    }
});

Much nicer and now looks like it was built in. You just have to avoid any existing property names (I used target as a custom before I realized it was an existing, rather important property) :)


Post a Comment for "How To Send Trigger Event And Know If It Was Cancelled/consumed By Any Recipient?"