0

In my backbone application, I am saving objects into local storage and only want to retrieve them once they are saved.

I tried using callback function (which fires after the function which saves data) but there is a bit of latency I observed and it returns undefined.

However, when I delay the function call (which retrieves the data) by 200 ms using setTimeout, it works just fine.

Is there an elegant way of doing it?

function delayed(){
    // this callback function retrieves the data
    callback.call(self);
}

window.setTimeout(delayed, 200);
cssyphus
  • 37,875
  • 18
  • 96
  • 111
Ankur
  • 1

3 Answers3

0

So you can make a custom wrapper for this purpose:

(function() {
    var Store = function() {
    };

    Store.prototype.set = function(key, value) {
        localStorage.setItem(key, value);
        return this.get(key);
    };

    Store.prototype.get = function(key) {
        return localStorage.getItem(key);
    };

    var store = new Store();
    console.log(store.set('foo', 'bar'));
})();

Fiddle

Eugene Naydenov
  • 7,165
  • 2
  • 25
  • 43
0

You could keep a duplicate outside of localStorage, in memory. You wouldn't need to rely localStorage's timing. Just write to localStorage often, and only load from it upon page load.

Just an idea! Without more specifics, it's hard to give a more concrete answer.

Reed Spool
  • 843
  • 7
  • 15
0

At first I thought of using the storage-event, but as you can see of this question - and this question, and this demonstration at html5demos.com, the use of the storage event is intended to track changes of the localstorage between windows / tabs, not inside the document itself.

But you can create your own event, firing when setItem is called by overriding setItem :

//create an "onstoragechange" custom event
var storageEvent = document.createEvent('Event');
storageEvent.initEvent('onstoragechanged', true, true);

document.addEventListener('onstoragechanged', function (e) {
    alert('value added to localstorage');
    //or 
    alert(localStorage.getItem('test'));
    //call the code here, as you above would do after setTimeout
    //"callback.call(self);" or whatever 
}, false);

//override localStorage.setItem
var oldSetItem = Storage.prototype.setItem;
Storage.prototype.setItem = function() { 
    oldSetItem.apply(this, arguments);
    document.dispatchEvent(storageEvent);
}

//test
localStorage.setItem('test', 'value');

demo / jsfiddle : http://jsfiddle.net/cYLHT/

Now you have an event that is dispatched each time you save anything to localStorage, and the written value actually is present. Expand this with events that helps out your application - like a special event if a certain important key is updated / stored. The above seems maybe as an "off topic" answer, or overkill, but I think it is a far better approach than spreading setTimeouts around the code.

Community
  • 1
  • 1
davidkonrad
  • 83,997
  • 17
  • 205
  • 265