fxb / javascript-last.fm-api

last.fm API bindings for JavaScript
http://lastfm.felixbruns.de/javascript-last.fm-api/
308 stars 53 forks source link

Caching does not work #10

Closed tburny closed 9 years ago

tburny commented 11 years ago

The object for caching is initialized wrong. An object needs to be used instead of an array.

For example in line 53 ff of lasfm.cache.js:

  localStorage.setObject(name, []);

use an object initializer:

  localStorage.setObject(name, {});

The same problem is within the clear() method.

Explanation: See the store() method:

    /* Store data in this cache with a given expiration time. */
    this.store = function(hash, data, expiration){
        var object = localStorage.getObject(name);
        var time   = Math.round(new Date().getTime() / 1000);

        object[hash] = {
            data       : data,
            expiration : time + expiration
        };

        localStorage.setObject(name, object);
    };

First, the object is de-serialized into an Array of length 0, thus

object=[] Then the property "hash" is set. This works because the type Array inherits Object. The resulting object would look similar to this:


object:Array
- length: 0
- "abc123123...a1234a": {.....}

where "abc123123...a1234a" is the value of the hash variable. During serialization, the hash property is lost as object is of type array and the length is 0, resulting in lastfm=[] in localStorage.

This is why lastfm={} should be stored in localStorage, making lastfm a json object with the hash values as keys.