I've worked a bit with jquery tools and I've started browsing through the twitter bootstrap src.
One thing I've noticed is the use of the $.Event
constructor for triggering events.
In many cases, (for instance the bootstrap modal) you find events triggered like so:
var e = $.Event('show');
this.$element.trigger(e);
It eludes me as to why this is better than just directly calling:
this.$element.trigger('show');
so I'm interested to know what the advantages are to using the jQuery Event constructor. I've read in the docs that you can attach arbitrary properties to the event, and that makes total sense to me. What I don't understand however is why it might be advantageous to use the constructor if you're not adding any properties to the event at all.
Can someone explain to me why the $.Event
constructor is an advantage over calling trigger with the event string?
Many thanks
It's a bit more flexible if you want to add properties to the event later on; and it helps you to know the state of the event after it was triggered, for instance, if someone called stopPropagation()
or preventDefault()
.
Other than that, jQuery will simply take the event type (string
), wrap it in a $.Event
object and normalize it. Here's the relevant source code of jQuery where this happens:
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With