durandaldurandal-2.0

Application ViewModel


How should application wide data be managed in a Durandal app?

For example, after the user logs in, I need to persist the UserName and UserId.

What I have tried is creating a singleton viewModel, and then import it where it is needed.

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

Is this the correct pattern to use with Durandal?


Solution

  • Here is a working example of using events for authentication:

    //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!
        });
    });