2

i have a poltergeist with this code:

javascript code:

var cache = {};

cache.init = function()
{   
    if(typeof(this.memory)=='undefined')
        this.memory = {};
};

cache.set = function(key, value)
{
    this.memory[key] = value;
};

cache.get = function(key)
{
    if(console)
    {
        console.log("memory: ");
        console.log(cache.memory);

        console.log("key: "+key);
        console.log(cache.memory[key]);
    }

    if(typeof(cache.memory[key])!='undefined')
        return cache.memory[key];

    return false;
};

var route = {};

route.load = function(url)
{
    var route_list = cache.get('route_list');

    if(route_list==false)
    {
        route_list = this.getList();
        cache.set('route_list', route_list);
    }

    return route_list;
};

route.getList = function()
{
    var result = false;
    $.ajax(
    {
        url: 'route.json',
        dataType: 'json',
        async: false,
        success: function(json)
        {
            result = json;
        }
    });
    return result;
};

cache.init();
route.load();
route.load();

i would like to cache some objects in client side with "cache" set and get.

content of route.json file:

{    
    "/example":
    {
        "controller":   "example"
    },
    "/example/show":
    {
        "controller":   "example",
        "method":   "show"
    }
}

and the result in firebug is:

memory:
Object
{
route_list
    Object { /example={...}, /example/show={...}}
}
key: route_list
undefined

why is undefined? i can navigate inside the object with firebug o.O

EDIT: i added the second call of route.load(); that i get undefined key

ZiTAL
  • 3,466
  • 8
  • 35
  • 50

2 Answers2

2

OK, now I can see your issue. Your code

route.load();
route.load();
  1. tries to get the [uncached] value from the cache:
    1. this logs the memory object
    2. and logs undefined because there is nothing
  2. because it returned false
    1. get the JSON synchronously
    2. and set it in the cache
  3. again tries to get the [cached] value
    1. logs the memory object
    2. and logs the cached object

Everything is executed correctly. Now, you see the memory object two times in your console - but it is the same object, in its current state when inspecting it and not in the state when you logged it. See also

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
0

the error comes from node.js:

    socket.emit('zapp_client', '/example');
    socket.emit('zapp_client', '/example/show');

i think it does asyncronously:

    socket.emit('zapp_client', '/example');
    setTimeout(function()
    {
        socket.emit('zapp_client', '/example/show');
    }, 1000);

with this i solved the problem temporarily...

ZiTAL
  • 3,466
  • 8
  • 35
  • 50