Can I listen for custom events in

I would like to use a custom event to let me app know that a route has changed. This way any components that care can listen and act accordingly. However I can’t seem to get custom events working outside of jquery… it would be really nice to add them to the… is this possible?

I have a situation where my header needs an active class to display the active CSS. Checking and setting the active class on click works for 90% of use cases but when the header switches out or it’s the first page load it won’t work quite right.

Currently i’m triggering Template.header.setActiveTabOnNavbar() from the AppController’s onAfterAction hook…which works great but i’d rather not mix header code in with the app router. I would really like to fire an event instead.

Is using jQuery trigger the only way?

1 Like

I feel like what you are doing here can be much more easily done with Spacebars directly, without resorting to setting classes manually using JQuery.

Is there some reason that approach didn’t work for you?

Thanks for the reality check @sashko ! I guess I was just used to doing it the imperative way :smile: . I reworked my templates to pass in the route name into the active helper.

Here’s a snippet in case someone else has the same trouble:

  active: function(linkName) {
    var routeName = Router.current().route.getName();
    return (routeName === linkName) ? ' active ' : '';

<ul class="nav navbar-nav navbar-right">
    <li class="{{active 'home'}}">
      <a href="/">Home</a>

    <li class="{{active 'posts'}}">
      <a href="/posts">Posts</a>

Great! Glad that helped :]

Just for completeness - as far as I know, listening to custom events in Template#events works fine. You just have to trigger the event on a DOM node that is inside the template.

1 Like

Here’s a Meteor Pad which has custom event handling within :
It works as one would expect event bubbling to work --parent Template elements can receive child element’s custom events, but siblings will not receive each other’s events. Perhaps a useful pattern for a long car trip with the kids :wink: