1

我试图根据用户是否登录来使某些按钮不可见,为此我做了类似的事情:

我有一个名为 authmodule 的模块,其编码为:

define(function () {

var loggedIn = ko.observable(false);  // tried without observable too.

var updateLoginStatus = function () {
    // call the webapi using ajax and intercept the 401
    // if error is 401 set set loggedIn to false and
    // true otherwise.

    // set ajax call
    var options = {
        url: '/breeze/breeze/MicCheck123',
        type: 'GET',
        dataType: 'json'
    };

    // make call
    return $.ajax(options)
        .then(function (data) {
            loggedIn(true);
        })
        .fail(function (jqXhr, textStatus) {
            if (jqXhr.status == 401 || jqXhr.status == 404) {
                loggedIn(false);
            }
        });
};

// my ko.computed used in html to do visible binding
var isUserLoggedIn = ko.computed(function () {
    updateLoginStatus();
    return loggedIn;
});

var authmodule = {
    isUserLoggedIn: isUserLoggedIn,
    updateLoginStatus: updateLoginStatus
};

return authmodule;
});

我现在在我的 shell.js 中需要这个 authmodule,并且还从 viewmodel 返回相同的,如下所示

define(['durandal/system',
    'services/logger',
    'durandal/plugins/router',
    'config',
    'services/authmodule'],
function (system, logger, router, config, authmodule) {

    var shell = {
        activate: activate,
        authmodule: authmodule,
        router: router
    };
    return shell;

    function activate() {
        return boot();
    }

    function boot() {
        router.map(config.routes);
        return router.activate(config.startModule);
    }
}
);

而对应的shell.js的html如下

    <div class="navbar-inner navbar-secondary">
    <div class="btn-group">
        <!-- ko foreach: router.visibleRoutes -->
        <a data-bind="attr: { href: hash },
                      css: { active: isActive },
                      html: caption,
                      visible: $parent.authmodule.isUserLoggedIn"
           class="btn btn-info"></a>
        <!-- /ko -->
    </div>
    </div>

由于我有四个可见的路线,并且我希望在 ajax 成功时在顶部功能区中看到 4 个按钮,而当 ajax 失败时,我希望看不到任何按钮,但无论 ajax 结果如何,这似乎都不起作用。

有人可以帮我确定我到底错过了什么吗?

我已经看过了

敲除锚标记的可见绑定不起作用

4

2 回答 2

1

我认为您不需要 isUserLoggedIn 属性。

所以,在按钮绑定替换

visible: $parent.authmodule.isUserLoggedIn

经过

visible: $parent.authmodule.loggedIn 

并在主视图模型中替换:

var isUserLoggedIn = ko.computed(function () {
    updateLoginStatus();
    return loggedIn;
});

经过 :

loggedIn.subscribe(updateLoginStatus);

我希望它有所帮助。

于 2013-06-18T15:10:06.473 回答
1

在 ko.computed 函数中,您需要调用 observable(这是 ko 在重新评估您的计算时知道的方式),例如

return loggedIn();

那么当该可观察值的值发生变化时,计算值也将被更新。

可能在您的示例中,ajax 调用应该只在计算范围内运行一次。

于 2013-06-18T16:06:16.363 回答