2

In my durandal app every page except the home page has a left navbar. This left navbar should be update on refresh, though it should reside on shell.html.

The problem is that i'm not being able to hide it properly on the home page. I can use jquery hide() method to hide the leftnav div when i'm on the home page, but the problem is that i can only use jquery code after data-bindind, and until there i can see the navbar. I tried to use durandal composition, but i'm not sure how can I hide the navbar only in the home page since i don't know how to know if i'm on the home page or not inside shell.js.

Any ideias?

Matthew James Davis
  • 12,134
  • 7
  • 61
  • 90
Pietro Coelho
  • 1,894
  • 1
  • 26
  • 34

1 Answers1

5

In your view model, you'll want to hook into your router by creating a computed that listens to the value of the current instruction:

var ko = require('knockout');
var router = require('plugins/router');

function viewModel() {
    this.currentRoute = ko.computed(function() {
        return router.activeInstruction().fragment;
    });
}

Then you can reference this variable using the visible binding in your view.

<!-- home route only -->
<div data-bind="visible: currentRoute() == 'home'></div>

<!-- non-home routes -->
<div data-bind="visible: currentRoute() != 'home'></div>

If you need more complicated logic, you can create a special computed function that does specific testing against the current route and reference that variable instead. For example:

this.isSpecialRoute = ko.computed(function() {
    var re = /matchspecialroute/;
    return re.test(this.currentRoute());
}, this);
Matthew James Davis
  • 12,134
  • 7
  • 61
  • 90
  • 2
    I just had to adapt the code a little bit: return router.activeInstruction().fragment only when router.aciveInstruction() is not null (just an if condition) Thanks! – Pietro Coelho Feb 25 '15 at 19:36
  • 3
    @MatthewJamesDavis Excellent answer! But do make sure that you dispose of your computed in the viewModel's `detached` handler. Otherwise, you'll leak like a sieve here. Better still, if you've upgraded to the latest version of KnockoutJS, you could use a `pureComputed` observable since there are no side effects in the computed you gave as part of your answer. –  Feb 26 '15 at 04:49
  • Just one more note: If your "home" view is your root, then you should compare currentRoute() with "" (empty string) instead of "home" – Pietro Coelho Feb 27 '15 at 15:14