Can I listen for custom events in Template.events?


#1

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 Template.foo.events… 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?


#3

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?


#4

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:

Template.header.helpers({
  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>

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

#5

Great! Glad that helped :]


#6

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.


#7

Here’s a Meteor Pad which has custom event handling within Template.events :
http://meteorpad.com/pad/pnAHjWFdqqeM98dda/Template%20Custom%20Events
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: