An EventEmitter that works over localStorage.
This module exposes a single class, EventEmitter
. Just create an instance of this class and start emitting events.
Creates a new EventEmitter, which lets you emit and listen for events.
The room ID is used to distinguish between different connections or rooms: when an EventEmitter emits an event, all open tabs in the same origin are notified of the event. With rooms, you can separate different channels: only EventEmitters with the same room ID as the source, will fire an event.
Rooms are optional: all emitters that don't have a room ID assigned, will behave as one room.
Options:
- attach: a boolean indicating whether to automatically start listening for events. Default: true
- emulate: a boolean indicating whether events should be emulated on the source emitter. When a key in localStorage is changed, all tabs in the same origin are notified, except the one that changed the key. Setting this to true (the default) will emulate the event on the source EventEmitter.
Private
An object mapping event names to arrays or registered listeners.
Read only
The room ID of this emitter.
Read only
The sanitized options for this emitter.
Read only
The version of the library.
Start listening for events; calls addEventListener
on origin
, or window
if origin
is not defined. Called automatically on creation when options.attach is not false
.
Stop listening for events; calls removeEventListener
on origin
, or window
if origin
is not defined.
Private
The listener for the storage
event.
Private
Emit event
on this emitter, i.e. call all listeners registered with this emitter.
Registers listener
on this emitter for event
.
Emits event
with some data. data
must be abel to be passed through JSON.stringify
and will be added to the event object as Event.data
.
The inner workings under the hood are actually fairly simple: to emit en event, the __events__
key in localStorage is changed to a specific string, formatted like this: <room ID>,<random ID>,<data>
.
<room ID>
is the room ID of the source emitter. Other emitters will check if it matches their ID.<random ID>
is a randomly generated 20-digit number. When the same event is emitted, with the same data in the same room, the string saved in localStorage wouldn't change without this random ID. In this case, thestorage
event wouldn't fire on the other pages.<data>
is an stringified JSON object, containing some info about the event. It is parsed at the other end os the line.