JQuery event constructor

I did a little work with jquery tools and I started browsing twitter bootstrap src .

One thing I noticed is using the constructor $.Eventto fire events.

In many cases (for example, a boot mod), you will find that events are fired like this:

var e = $.Event('show');

this.$element.trigger(e);

This eludes me why this is better than just a direct call:

this.$element.trigger('show');

therefore, I am interested to know the benefits of using the jQuery event constructor. I read in the docs that you can attach arbitrary properties to an event, and that makes sense to me. However, I do not understand why it would be useful to use a constructor if you do not add any properties to the event at all.

Can someone explain to me why a constructor $.Eventis an advantage over invoking a trigger using an event string?

Many thanks

+5
source share
2 answers

After viewing the source file, I believe that you should keep in mind the following:

var that = this
    , e = $.Event('show')

this.$element.trigger(e)

if (this.isShown || e.isDefaultPrevented()) return

He determines ethat he can later check if the default action was prevented with e.isDefaultPrevented().

0
source

This is a bit more flexible if you want to add properties to the event later; and this will help you know the state of the event after it is triggered, for example, if someone called stopPropagation()or preventDefault().

, jQuery (string), $.Event . jQuery, :

event = typeof event === "object" ?
     // jQuery.Event object
     event[ jQuery.expando ] ? event :
     // Object literal
     jQuery.extend( jQuery.Event(type), event ) :
     // Just the event type (string)
     jQuery.Event(type);
+1

All Articles