Session Data with Durandal

回眸只為那壹抹淺笑 提交于 2019-11-28 06:39:54

问题


I am just getting started with Durandal.js so excuse me for the silly quesstion...

When a user makes it's first request to the app it is asked to choose a 'profile kind', and I need it to be accessible to every other view model in the web site, I first though of creating this property in the shell viewmodel, but don't how to do it.

How is the best way to store data in a Session like mode in a Durandal SPA?

Thanks!


回答1:


Create an amd module for what data you need to store.

Then just require that module as a dependency for whatever other modules that need it.

Sort of like this:

session module

define(function () {
    return {
        someVariable: 'value1',
        someVariable2: 'value2'
    }
})

some other module

define(['session'], function(session) {
    return {
        getValue1: function () {
            return session.someVariable;
        },
        obs1: ko.observable(session.someVariable2)
    }
})

EDIT** AMD modules are there to not pollute the global namespace of the window object. But if you would rather not require your session as a dependency and just access it through a global variable then that is perfectly fine.

you can declare it in your shell.js if you would like and do something like:

define(function () {
    window.session = { someVariable: 'value1', someVariable2: 'value2' };
})

then inside some other module you can access the session object like so:

define(function() {
    return {
        getValue1: function () {
            return session.someVariable;
        },
        obs1: ko.observable(session.someVariable2)
    }
})

This information will not be persisted between page refreshes.. its only in-memory. If your looking to persist the session data I would not look into persisting any information on the client unless you planned on making your app an off-line application. An offline application is an app that works even w/out internet access. But if your app requires that the user is always connected to the internet then I would just store the session data on the server. So, just use web services to persist the session data and retrieve it.

You can tie the session on the server to the client by using a cookie.




回答2:


As an alternative to Evan's answer, which is definitively the correct AMD approach... have you considered using a global object for that purpose?

in main.js

window.myApp = {
    prop1: 'value',
    subOne: {
         prop1: 'value'
    } 
   ... 
}

That will allow you to access the global myApp object everywhere. I know that some people will consider that as global namespace pollution and in general a bad practice, but in a SPA project (where you control window) I'd consider this still a viable approach.



来源:https://stackoverflow.com/questions/17490401/session-data-with-durandal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!