• home > webfront > SGML > html5 >

    localStorge之storage事件

    Author:[email protected] Date:

    随着h5的流行和mobile开发,localStorage已经不再是个陌生词,相信大多数童鞋都已经接触过它并用过,但是storage事件相信还是有很多童鞋不太明白甚至没接触过,今天我们主要聊聊storage。

    随着h5的流行和mobile开发,localStorage已经不再是个陌生词,相信大多数童鞋都已经接触过它并用过,但是storage事件相信还是有很多童鞋不太明白甚至没接触过,今天我们主要聊聊storage。


    先看w3c关于storage都描述:

    4.4 The storage eventThe storage event is fired when a storage area changes, as described in the previous two sections (for session storage, for local storage).
    
    
    When this happens, the user agent must queue a task to fire an event with the name storage, which does not bubble and is not cancelable, and which uses the StorageEvent interface, at each Window object whose Document object has a Storage object that is affected.

    它说得很清晰,当存储的storage数据发生变化时都会触发它,但是它不同于click类的事件会冒泡和能取消,同时最后这句才是重点,storage改变的时候,触发这个事件会调用所有同域下其他窗口的storage事件,不过它本身触发storage即当前窗口是不会触发这个事件的(当然ie这个特例除外,它包含自己本事也会触发storage事件)。这句话说的有点绕口,看代码把。


    DEMO:

    页面a下,有个input框用来存储store,它自身绑定了storage事件,这个时候写入新的数据点击保存,这时新的sotre数据保存了,但是页面a的storage事件没触发,

    而页面b下,绑定的storage事件则触发了。(ps:前提页面a和b在同域下,并都是打开状态不同窗口);

    页面a代码:


    <!DOCTYPE html>  
    <html>  
    <head>  
      <meta charset="utf-8">  
      <title></title>  
    </head>  
    <body>  
    <input type="text" placeholder="input date to save">  
    <button>save</button>  
    <script>  
      (function(D){  
        var val = D.getElementsByTagName("input")[0],  
          btn = D.getElementsByTagName("button")[0];  
        btn.onclick = function(){  
          var value = val.value;  
          if(!value) return;  
          localStorage.setItem("key", val.value);  
        };  
        window.addEventListener("storage", function(e){  
          console.log(e);  
        });  
      })(document);  
    </script>  
    </body>  
    </html>

    <!DOCTYPE html>  
    <html>  
    <head>  
      <meta charset="utf-8">  
      <title></title>  
    </head>  
    <body>  
    <script>  
      window.addEventListener("storage", function(e){  
        console.log(e);  
        document.write("oldValue: "+ e.oldValue + " newValue:" + e.newValue)  
      });  
      
    </script>  
    </body>  
    </html>


    看到这里是不是很疑惑那storage事件到底有什么用,多窗口间多通信用到它就是最好选择了,比如某块公用内容区域基础数据部分都是从store中提取的,这个区域中大多数页面中都有,当用户打开多个页面时,在其中一个页面做了数据修改,那其他页面同步更新是不是很方便(当前页面就要用其他方式处理了),当然用于窗口间通信它作用不仅仅如此,更多的大家可以利用它特性去发挥。

    ps:

    顺带补充下,在上面的demo页面b中storage的events对象的属性常用的如下: 

     oldValue:更新前的值。如果该键为新增加,则这个属性为null。 

     newValue:更新后的值。如果该键被删除,则这个属性为null。

     url:原始触发storage事件的那个网页的网址。 

     key:存储store的key名;


    另外store虽好可不要贪“杯”噢,大量冗余数据存储最后可是灾难,而且store安全性有限,重要数据也要注意。

    文章来源:http://blog.csdn.net/nx8823520/article/details/30478859


    转载本站文章《localStorge之storage事件》,
    请注明出处:https://www.zhoulujun.cn/html/webfront/SGML/html5/2016_0406_7737.html