应用程序ViewModel

时间:2015-04-20 17:08:59

标签: durandal durandal-2.0

如何在Durandal应用程序中管理应用程序范围的数据?

例如,在用户登录后,我需要保留UserName和UserId。

我尝试过创建一个单例viewModel,然后将其导入到需要它的位置。

define(['knockout'], function (ko) {
return {
    currentUser: ko.observable(),    
};
});

这是与Durandal一起使用的正确模式吗?

2 个答案:

答案 0 :(得分:1)

以下是使用事件进行身份验证的工作示例:

//app/auth.js
'use strict';

define(function (require) {
    var
        ko = require('knockout'),
        User = require('auth/model/user'),
        api = require('auth/api'),
        events = require('durandal/events'),

        guestUser = new User({id: null}),
        currentUser = ko.observable(guestUser),

        signedIn = ko.computed(function () {
            return ko.unwrap(currentUser().id) !== null;
        }),

        load = function () {
            return api.getUser().then(function (dto) {
                var user = User.mapper.fromDto(dto);
                currentUser(user);

                return user;
            });
        },

        signIn = function (username, password, remember) {
            var that = this;
            return api.signIn(username, password, remember)
                .then(function (data) {
                    var user = User.mapper.fromDto(data);
                    currentUser(user);

                    that.trigger('signin:success', user);

                    return user;
                }, function (reason) {
                    that.trigger('signin:failure', reason);

                    throw reason;
                });
        },

        signOut = function () {
            var that = this;
            currentUser(guestUser);

            return api.signOut().then(function () {
                that.trigger('signout:success');
            });
        };

    return {
        load: load,
        signIn: signIn,
        signedIn: signedIn,
        signOut: signOut,
        currentUser: currentUser
    }
});

//main.js

define(function (require) {
   var auth = require('auth'),
       events = require('durandal/events'); 

   events.includeIn(auth);
});


//mysecuremodule.js

define(function (require) {
   var auth = require('auth');

   auth.on('signin:success').then(function (user) {
     //hello signed in user!
    });
});

答案 1 :(得分:0)

我找到了一个更好的答案,那就是使用内置于Durandal中的events。这很有效。