Session Data with Durandal

前端 未结 2 1334
悲&欢浪女
悲&欢浪女 2020-12-20 09:11

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

相关标签:
2条回答
  • 2020-12-20 10:05

    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.

    0 讨论(0)
  • 2020-12-20 10:08

    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.

    0 讨论(0)
提交回复
热议问题