Skip to content

Instantly share code, notes, and snippets.

@rossgoodwin
Forked from monostere0/GlobalEvents.js
Last active August 29, 2015 14:12
Show Gist options
  • Save rossgoodwin/574658c650a82a1afc2d to your computer and use it in GitHub Desktop.
Save rossgoodwin/574658c650a82a1afc2d to your computer and use it in GitHub Desktop.
(function(window){
var EVENT_EXISTS = 'GlobalEvents: Event already exists.';
var eventIsRunning,
_eventStack,
_findByName,
stackEvent,
removeEvent,
eventListener,
listen, unlisten,
_set, _rem, _parse,
_storage;
_storage = window.localStorage;
eventIsRunning = false;
_eventStack = [];
_findByName = function (eventName) {
var evArray = _eventStack.filter(function(ev) {
return ev.name === eventName;
});
return evArray.length ? evArray[0] : null;
};
stackEvent = function (eventName, callback, args) {
if (_findByName(eventName)) {
throw EVENT_EXISTS;
} else {
var ev = {
name: eventName,
callback: callback
};
if (args) {
ev.args = args;
}
_eventStack.push(ev);
}
};
removeEvent = function (eventName) {
var ev = _findByName(eventName);
var idx = _eventStack.indexOf(ev);
_eventStack.splice(idx, 1);
};
eventListener = function (e) {
var ev = _findByName(e.key),
val = e.newValue,
params = [];
if (ev && !eventIsRunning) {
eventIsRunning = true;
ev.args && params.push(ev.args);
val && val !== '_evt' && params.push(_parse(val));
ev.callback.apply(this, params);
setTimeout(function() {
eventIsRunning = false;
}, 10);
}
};
listen = function () {
window.addEventListener('storage', eventListener);
};
unlisten = function () {
window.removeEventListener('storage', eventListener);
};
_set = function (key, value) {
return _storage.setItem(key, value || '_evt');
};
_rem = function (key) {
return _storage.removeItem(key);
};
_parse = function (val) {
try {
return JSON.parse(val);
} catch (e) {}
return val;
};
function GlobalEvents() {
//begin listening for events
unlisten();
listen();
};
GlobalEvents.prototype = {
on: stackEvent,
off: removeEvent,
trigger: function (eventName, transportObject) {
_set(eventName, transportObject);
unlisten();
setTimeout(function() {
_rem(eventName);
listen();
});
}
};
window.GlobalEvents = new GlobalEvents();
})(window);
//usage #1 - trigger the event
//listen to the event in one window
GlobalEvents.on('test', function() {
//do something when the event fires
});
//fire the event from another window
GlobalEvents.trigger('test');
//usage #2 - trigger the event an transport an object between windows
//listen to the event in one window
GlobalEvents.on('test', function(transportObj) {
//do something with transportObj when the event fires
});
//fire the event from another window and send an object
GlobalEvents.trigger('test', {foo:bar,baz:bar});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment