4

I understand how to trigger and listen for custom events. I can't figure out how Bootstrap is listening to custom events without triggering them.

https://github.com/twitter/bootstrap/blob/master/js/bootstrap-scrollspy.js#L32

Nowhere in their code can I find where they are triggering that custom scroll event. I took a look at the jQuery on docs and couldn't see if events are naturally namespaced somehow.

How does this work?

1
  • Thanks for asking this question. I was baffled by this as well. Commented Oct 31, 2013 at 10:14

1 Answer 1

4

They're listening to the scroll event which is a naturally occurring event. It's not a custom event, they've just namespaced it. The reason for namespacing it is so you can remove all events by just removing the namespace from all events. Look at Using Namespaces in unbind.

Sign up to request clarification or add additional context in comments.

4 Comments

Oh, I see. So by listening for 'scroll.*" it automatically just matches events of type "scroll". What if you triggered a custom event called "scroll.foo" but you were listening for "scroll.bar"?
I'm not sure, I have not tried that. But, yea. Listening for "scroll.bar" or "scroll.foo" will catch each trigger('scroll') and real scroll event. The namespace is mainly for easy/clean removal.
@kmiyashiro: Try this: $(window).on('scroll.bar', function () { alert('scroll.bar') }).trigger('scroll.foo'); vs. $(window).on('scroll.bar', function () { alert('scroll.bar') }).trigger('scroll.bar'); - the first alert won't show whereas the second one will.
Yeah, I got it. It seems like it's mostly for removing listeners rather than triggering them, though. I was initially thought it was used more for namespacing the triggered events themselves.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.