我试图根据用户是否登录来使某些按钮不可见,为此我做了类似的事情:
我有一个名为 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 结果如何,这似乎都不起作用。
有人可以帮我确定我到底错过了什么吗?
我已经看过了