Search code examples
meteorspacebars

Tabbing in Meteor - Understanding Microscope Example


I'm trying to understand this code from Discover Meteor's Microscope Project:

https://github.com/DiscoverMeteor/Microscope/blob/master/client/templates/includes/header.js

It's for making the current route's tab active on the page by adding an 'active' class to the tab, but there are some pieces of code I'm not understanding. Specifically:

 return Router.current() && Router.current().route.getName() === name

I don't understand where name is coming from, and why it's necessary. Are there routing cases with iron:router where Router.current() won't return true (such as server-side routes)?

I'm also confused about why a boolean is returned along with the class in the helper function:

 return active && 'active';

Does Spacebars only apply the 'active' class to the tab if the boolean returns true? Could someone point to more information about how this works with Spacebars, if this is the case?

Many thanks.


Solution

  • I don't understand where name is coming from

    The name variable is the argument of the predicate function passed to the _.any iterator function (http://underscorejs.org/#some), so basically it's an iteration over every argument of the helper (stored in the args variable) to see if any of them matches the predicate function.

    The return value of the predicate function will be true if at least one argument of the helper passes the predicate test, which is comparing the current route name against the currently iterated value.

    Are there routing cases with iron:router where Router.current() won't return true

    Router.current() as the name implies, is a reactive data source returning the current RouteController, so it's possible that it might return a non-truthy value at some point (in particular when the app is first initialized).

    return active && 'active';
    

    Concerning this line of JS, it has little to do with Spacebars, it's just a common JS trick where a boolean expression consisting in a succession of AND operators stops being executed when it encounters a falsy value and returns the last value parsed.

    It means that if active is false then it immediatly returns false, but if it's true then the whole expression returns the 'active' string.

    The only place where Spacebars is involved is that when a helper used as an HTML attribute value evaluates to a falsy value, then the attribute does not make it way to the DOM.

    I personally use this syntax which I find less obscure but this is primarily opinion-based.

    return active?"active":"";