2013-09-27 61 views
0

在我的骨幹應用程序中,我將對象保存到本地存儲中,並且只需要在保存對象時檢索它們。在使用javascript進行保存之後從瀏覽器本地存儲中檢索數據

我試過使用回調函數(在保存數據的函數之後觸發),但是我觀察到有一點延遲,它返回undefined。

但是,當我使用setTimeout將函數調用(它檢索數據)延遲200毫秒時,它工作得很好。

有沒有一種優雅的方式呢?

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

window.setTimeout(delayed, 200); 
+0

更多的代碼會使它更容易幫助。 – EmptyArsenal

+0

保存到localStorage是即時的...如果您願意,可以在下一行檢索值。 – david

+0

它是_synchronous_,不是即時:) –

回答

0

所以,你可以做一個定製的包裝用於此目的:

(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

0

你可以保持一個重複的localStorage之外,在內存中。你不需要依賴localStorage的時間。只需經常寫入localStorage,並且只在頁面加載時從它加載。

只是一個想法!沒有更多細節,很難給出更具體的答案。

0

起初我以爲使用存儲的事件,但你可以看到this question - 在html5demos.com和this question,並且this demonstration,使用存儲事件的目的是跟蹤之間的localStorage的的變化窗口/選項卡,不在文檔本身內。

但你可以創建自己的事件,射擊時setItem是通過覆蓋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'); 

演示/的jsfiddle:http://jsfiddle.net/cYLHT/

現在您有每次保存任何東西分派的事件到localStorage,並且書面價值實際上是存在的。通過幫助您的應用程序的事件進行擴展 - 如果某個重要密鑰更新/存儲,就像是一個特殊事件。以上看起來可能是一個「off topic」的答案,或者是過度的,但我認爲這比在代碼周圍傳播setTimeouts更好。

相關問題