Skip to content

Listen to storage events and re-fire if item changed used lscache #53

Description

@iabw

I was trying to hook onto some storage events, and I realized lscache doesn't have helpers for this. Something like

if (window.addEventListener) {
  // Normal browsers
  window.addEventListener("storage", handler, false);
} else {
  // for IE
  window.attachEvent("onstorage", handler);
};

function handler(e) {
  var index = e.key.indexOf('lscache-');
  if (index === 0){
    lscache.trigger(e.key.substr(8), e);
  }
}

would let us do something like

lscache.on('myKey',callback);

This seems cool, right?

You'd also have to add the on/trigger functionality, something like this minimal example.

    on: function(event, callback, context) {
      this.hasOwnProperty('events') || (this.events = {});
      this.events.hasOwnProperty(event) || (this.events[event] = []);
      this.events[event].push([callback, context]);
    },
    trigger: function(event) {
      var tail = Array.prototype.slice.call(arguments, 1),
          callbacks = this.events[event];
      for(var i = 0, l = callbacks.length; i < l; i++) {
        var callback = callbacks[i][0],
            context = callbacks[i][1] === undefined ? this : callbacks[i][1];
        callback.apply(context, tail);
      }
    }

If performing the handler on every storage event isn't preferable, this functionality could hide behind an initialization flag or a helper like lscache.startFiringEvents().

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions