Как отслеживать маршрут из оболочки Durandal?

Все, что мне нужно, это следить за текущим маршрутом, чтобы некоторые вычисляемые наблюдаемые объекты обновлялись соответствующим образом. Соответствующий код с объяснением в комментариях:

define(['durandal/plugins/router', 'durandal/app','services/dataservice'], function (router, app, dataservice) {

    // TODO: I need to make these computed observables that monitor the route, but I can't monitor the route until after it's been activated, so I just define these guys as observables here
    this.isViewingFolder = ko.observable();
    this.isViewingSet = ko.observable();

    // These don't evaluate correctly because isViewingFolder() doesn't get defined until after the DOM loads (I think)
    var displayAddForFolder = ko.computed(function () {
        return selectedItemsCount() == 0 && isViewingFolder() && !isViewingSet();
    });
    var displayAddForSet = ko.computed(function () {
        return selectedItemsCount() == 0 isViewingSet() && !isViewingFolder();
    }); 

    // The ONLY way I've been able to get this to work is with the following (putting a computed into an observable??)
    var viewAttached = function () {
        isViewingFolder(ko.computed(function() {
            return router.activeRoute().moduleId == 'viewmodels/folder';
        }));
        isViewingSet(ko.computed(function () {
            return router.activeRoute().moduleId == 'viewmodels/set';
        }));
    }

    // If I try this the value updates once but only once, never again:
    var viewAttached = function () {
        isViewingFolder(router.activeRoute().moduleId == 'viewmodels/folder');
        isViewingSet(ko.computed(router.activeRoute().moduleId == 'viewmodels/set');
    }

Любая помощь приветствуется. Все выходные ломал голову над этим.


person RobVious    schedule 03.06.2013    source источник


Ответы (1)


Разве это не вариант вашего вопроса? 16646947">Durandal: Определение того, активно ли представление в данный момент (возможно, с помощью маршрутизатора)?. Здесь применим тот же ответ.

Предположим, что ваша оболочка возвращает синглтон, что-то вроде следующего должно делать то, что вы ищете.

define(['durandal/plugins/router', 'durandal/app','services/dataservice'], function (router, app, dataservice) {

var isViewingFolder = ko.observable(false);
var isViewingSet = ko.observable(false);

router.activeRoute.subscribe(function( val ) {
      isViewingFolder(val.moduleId === 'viewmodels/folder');
      isViewingSet(val.moduleId === 'viewmodels/set');
      console.log('isViewingFolderOrSet', isViewingFolder(), isViewingSet());

  });
...


return {
    router: router,
    isViewingFolder: isViewingFolder,
    isViewingSet: isViewingSet,
    ...
   }
});
person RainerAtSpirit    schedule 03.06.2013
comment
Да я просто не мог понять, как заставить его работать. Спасибо, Райнер. - person RobVious; 03.06.2013