Question

In the example below (and in the jsfiddle, dependant on requirejs) the console outputs theUsername and http://nothing&username=null the first time through and then if you run it again it outputs as you'd expect (i.e., http://nothing&username=theUsername)

define('environment', {
    myData: 'http://nothing&username=' + sessionStorage.getItem('username')
});

require(['environment'], function (environment) {
    sessionStorage['username'] = 'theUsername';

    console.log(sessionStorage.getItem('username'));
    console.log(environment.myData);
});

Previous edits

I couldn't figure out how to set this up in a jsfiddle with all the dependencies, but here is a simple version demonstrating the problem in azure. The page doesn't actually do anything and hits a dead connection string so you'll have to look at it through the browser dev tools or firebug.

http://tomdev.azurewebsites.net/www/index.html

Ok, hopefully the last update... I was able to get this displaying the problem in jsfiddle, very simple, small example. Watch the console in Chrome. Run it once and you'll see the problem, hit run again and you'll see it's working now.

http://jsfiddle.net/JhK5L/1/

Was it helpful?

Solution

You're initializing myData in your define() call with whatever value is in sessionStorage['username']. Therefore, the first time you call define() the value is null, and is not set until you initialize sessionStorage['username'] in your require() function.

Instead of initializing myData to a string, make it a getter function that retrieves the current value at invocation:

define('environment', {
    myData: function() { return 'http://nothing&username=' + sessionStorage.getItem('username'); }
});

require(['environment'], function(environment) {
    sessionStorage['username'] = 'theUsername';

    $("ul").append('<li>' + sessionStorage.getItem('username') +'</li>');
    $("ul").append('<li>' + environment.myData() +'</li>');
});

OTHER TIPS

This is an issue with requiring the environment module before running the code. When you do require(['environment'], function () { it will find AND run the environment module BEFORE anything else gets run. This means whatever is in session storage at the time is what gets outputted. Then, it runs the function, which sets up the session storage to what it should be.

Once the function is run, you need to update the myData variable with the new value, as it has already "cached" the old one, which was undefined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top