【问题标题】:Retrieving data from browser local storage after saving it using javascript使用javascript保存后从浏览器本地存储中检索数据
【发布时间】:2013-09-27 21:27:27
【问题描述】:

在我的主干应用程序中,我将对象保存到本地存储中,并且只想在保存后检索它们。

我尝试使用回调函数(在保存数据的函数之后触发),但我观察到有一点延迟,它返回未定义。

但是,当我使用 setTimeout 将函数调用(检索数据)延迟 200 毫秒时,它工作得很好。

有没有优雅的方法?

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

window.setTimeout(delayed, 200);

【问题讨论】:

  • 更多代码会更容易提供帮助。
  • 保存到 localStorage 是即时的...如果需要,您可以检索下一行的值。
  • 它是同步的,不是即时的 :)

标签: javascript backbone.js


【解决方案1】:

因此您可以为此目的制作自定义包装器:

(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

【讨论】:

    【解决方案2】:

    您可以在 localStorage 之外的内存中保留一个副本。您不需要依赖 localStorage 的时间。只需经常写入 localStorage,并仅在页面加载时从其中加载。

    只是一个想法!没有更多细节,很难给出更具体的答案。

    【讨论】:

      【解决方案3】:

      一开始我想使用 storage-event,但正如您在 html5demos.com 上看到的 this question - 和 this questionthis demonstration,使用 storage 事件是为了跟踪窗口/选项卡之间的本地存储,而不是在文档本身内部。

      但您可以创建自己的事件,在通过覆盖 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 时都会调度一个事件,并且写入的值实际上是存在的。使用有助于您的应用程序的事件来扩展它——比如更新/存储某个重要键时的特殊事件。以上似乎是一个“离题”的答案,或者矫枉过正,但我​​认为这比在代码中传播 setTimeouts 更好。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-15
        • 2022-12-08
        • 2014-12-26
        • 1970-01-01
        • 2023-03-29
        • 2014-10-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多