Durandal/Knockout. Update other view/viewmodel
Asked Answered
J

1

8

Durandal has a base view called shell.

I've added a searchbox on it to allow admin/quality assurance users to mimic any system user. On the button click I want to be able to update the view of whichever view is currently displayed.

  • Shell (Blue) View (Red)

How would I go about, exposing a function on my child view so that I can call it from shell, or hook into the button click event of shell from the child view.

Question:

Does Durandal expose any hooks that I can make use of to bubble or pass events to different views or parent containers?

Janeejaneen answered 22/7, 2013 at 7:32 Comment(0)
B
11

Assuming you have multiple child views and don't want to introduce dependencies between shell and children it's probably best to use Durandal's event system for this. The shell view would become the publisher and the child views subscribers.

Check out http://dfiddle.github.io/dFiddle-1.2/#/event-aggregator/dFiddle for a working demo.

publisher.js

define(['durandal/app'], function (app) {

    var message = ko.observable();
    var canPublish = ko.computed(function () {
        return message() ? true : false;
    });

    return {
        message: message,
        canPublish:canPublish,
        publish: function () {
            app.trigger('sample:event', message());
        }
    };
});

subscriber.js

define(['durandal/app'], function (app) {

    return {
        received: ko.observableArray([]),
        subscription:ko.observable(),
        subscribe: function () {
            var sub = app.on('sample:event').then(function(message) {
                this.received.push(message);
            }, this);

            this.subscription(sub);
        },
        unsubscribe: function () {
            this.subscription().off();
            this.subscription(null);
        }
    };
});

Other options that could be considered

  • a shared module that returns a singleton with properties that should be shared between parent/childs. Drawback it needs to be defined as dependency in all parent/childs.
  • one global e.g. myApp with properties... Drawback: exposing a global
Bourgeon answered 22/7, 2013 at 8:35 Comment(1)
This is such a damn cool solution. :) Thanks for all the help again Rainer.Stoichiometric

© 2022 - 2024 — McMap. All rights reserved.