316376f2e84f9b14326eab060bff97828f42ae9bbbeb493b40f69480905c5668f549d83adab581b3b8a2ca020009777bc38197516612c47b0a3061739b4578 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /**
  2. * Copyright (c) 2013 ESHA Research
  3. * Dual licensed under the MIT and GPL licenses:
  4. * http://www.opensource.org/licenses/mit-license.php
  5. * http://www.gnu.org/licenses/gpl.html
  6. *
  7. * Makes it easy to watch for storage events by enhancing the events and
  8. * allowing binding to particular keys and/or namespaces.
  9. *
  10. * // listen to particular key storage events (yes, this is namespace sensitive)
  11. * store.on('foo', function listenToFoo(e){ console.log('foo was changed:', e); });
  12. * store.off('foo', listenToFoo);
  13. *
  14. * // listen to all storage events (also namespace sensitive)
  15. * store.on(function storageEvent(e){ console.log('web storage:', e); });
  16. * store.off(storageEvent);
  17. *
  18. * Status: BETA - useful, if you aren't using IE8 or worse
  19. */
  20. ;(function(window, _) {
  21. _.on = function(key, fn) {
  22. if (!fn) { fn = key; key = ''; }// no key === all keys
  23. var s = this,
  24. listener = function(e) {
  25. var k = s._out(e.key);// undefined if key is not in the namespace
  26. if ((k && (k === key ||// match key if listener has one
  27. (!key && k !== '_-bad-_'))) &&// match catch-all, except internal test
  28. (!e.storageArea || e.storageArea === s._area)) {// match area, if available
  29. return fn.call(s, _.event.call(s, k, e));
  30. }
  31. };
  32. window.addEventListener("storage", fn[key+'-listener']=listener, false);
  33. return this;
  34. };
  35. _.off = function(key, fn) {
  36. if (!fn) { fn = key; key = ''; }// no key === all keys
  37. window.removeEventListener("storage", fn[key+'-listener']);
  38. return this;
  39. };
  40. _.once = function(key, fn) {
  41. if (!fn) { fn = key; key = ''; }
  42. var s = this, listener;
  43. return s.on(key, listener = function() {
  44. s.off(key, listener);
  45. return fn.apply(this, arguments);
  46. });
  47. };
  48. _.event = function(k, e) {
  49. var event = {
  50. key: k,
  51. namespace: this.namespace(),
  52. newValue: _.parse(e.newValue),
  53. oldValue: _.parse(e.oldValue),
  54. url: e.url || e.uri,
  55. storageArea: e.storageArea,
  56. source: e.source,
  57. timeStamp: e.timeStamp,
  58. originalEvent: e
  59. };
  60. if (_.cache) {
  61. var min = _.expires(e.newValue || e.oldValue);
  62. if (min) {
  63. event.expires = _.when(min);
  64. }
  65. }
  66. return event;
  67. };
  68. // store2 policy is to not throw errors on old browsers
  69. var old = !window.addEventListener ? function(){} : null;
  70. _.fn('on', old || _.on);
  71. _.fn('off', old || _.off);
  72. _.fn('once', old || _.once);
  73. })(window, window.store._);