【问题标题】:How to monitor route from Durandal shell?如何从 Durandal shell 监控路线?
【发布时间】:2013-06-03 16:00:22
【问题描述】:

我所需要的只是监控当前路线,以便一些计算出的 observables 相应地更新。 cmets中带解释的相关代码:

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');
    }

任何帮助将不胜感激。整个周末都在为此头疼。

【问题讨论】:

    标签: knockout.js durandal


    【解决方案1】:

    这不是您的问题Durandal: Determining if a view is currently active (possibly using Router)? 的变体。 同样的答案也适用于此。

    假设您的 shell 返回一个单例,如下所示应该可以满足您的需求。

    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,
        ...
       }
    });
    

    【讨论】:

    • 是的,我只是不知道如何让它工作。谢谢雷纳
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    • 2019-11-28
    • 1970-01-01
    相关资源
    最近更新 更多