Stas Slabko
Stas Slabko

Reputation: 516

Durandal: Switch views without reloading model

I am using duraldal v2, and on one of the pages I want to switch views without re-activating the model.

To achieve this I leverage approach from v1 using compose binding with view connected to observable, changed by inline click binding in my navigation links:

    <ul class="nav nav-tabs">
        <li data-bind="css: {active:activeView() == 'view1'}"><a href="#" data-bind="click: function(){setView('view1')}">View 1</a></li>
        <li data-bind="css: {active:activeView() == 'view2'}"><a href="#" data-bind="click: function(){setView('view2')}">View 2</a></li>
        . . .
    </ul>
    <div data-bind="compose: {view: activeView, activate: true, area: 'settings', transition: 'entrance', cacheViews: true}"></div>

VM:

define(['knockout'], function (ko) {
return {
    activeView: ko.observable()
    ,setView: function(view) {
        this.activeView(view);
    }
    ,activate: function (args) {
        var self = this;
        return system.defer(function(dfd) {
            self.setView('view1');
            dfd.resolve(true);
        }).promise();
    }
    . . . 

I believe this is an awkward way, and in v2 there should be a more elegant way to do this. As far as understand, I cannot use child router, like in ko samples, because it reloads model every time.

Any ideas?

Upvotes: 0

Views: 605

Answers (1)

Shaun Rowan
Shaun Rowan

Reputation: 9539

Looks fine to me.

Is it the inline functions you dislike? You could just do:

    <ul class="nav nav-tabs">
        <li data-bind="css: {active:activeView() == 'view1'}"><a href="#" data-bind="click: setView1">View 1</a></li>
        <li data-bind="css: {active:activeView() == 'view2'}"><a href="#" data-bind="click: setView2">View 2</a></li>
        . . .
    </ul>

and:

return {
    activeView: ko.observable()
    ,setView1: function() { this.activeView('view1') },
    ,setView2: function() { this.activeView('view2') },
...

If this functionality is really common for you, you might consider turning it into a widget which could potentially box up a pattern like this.

Upvotes: 1

Related Questions