5

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

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

While everything here is correct, it doesn't mention the use of $.Event in the bootstrap modal plugin. In bootstrap modal he defines the event object so he can check for isDefaultPrevented later.
thanks for the answer João, that gives me more insight into how jQuery works with events, @Fauntleroy got the explanation of this right in the context of bootstrap. Thanks again!
0

After taking a look at the bootstrap source, I believe you must be referring to this:

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

this.$element.trigger(e)

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

He's defining e so that he can later check to see if the default action has been prevented with e.isDefaultPrevented().

1 Comment

ah... you're absolutely right. I don't know how I missed that. thx!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.