Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Durandal/Knockout. Update other view/viewmodel

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?

like image 747
Rohan Büchner Avatar asked Jul 22 '13 07:07

Rohan Büchner


1 Answers

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
like image 113
RainerAtSpirit Avatar answered Oct 17 '22 11:10

RainerAtSpirit