Skip to content

Instantly share code, notes, and snippets.

@thlemercier
Created October 18, 2020 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thlemercier/af156f86f6fb09c8cbf97a7a1f291472 to your computer and use it in GitHub Desktop.
Save thlemercier/af156f86f6fb09c8cbf97a7a1f291472 to your computer and use it in GitHub Desktop.
class Observer {
/**
*
* @param {*} observerKey Uniq key to identify the observer
* @param {*} eventName The event name to listen on
* @param {*} fn The function to run when the event is called
*/
constructor(observerKey, eventName, fn) {
this.fn = fn;
this.eventName = eventName;
this.observerKey = observerKey;
}
update(content) {
if(typeof this.fn === 'function') {
this.fn(content);
}
}
}
class Subject {
constructor () {
this.observers = [];
}
subscribe (observerKey, eventName, fn) {
this.observers.push(new Observer(observerKey, eventName, fn));
}
notify (eventName, value) {
this.observers.filter(s => s.eventName == eventName).forEach(s => s.update(value));
}
unsubscribe (observerKey) {
this.observers = this.observers.filter(o => o.observerKey !== observerKey);
}
}
const vueTabEvents = {
install: function (Vue) {
const subject = new Subject();
Vue.prototype.$LocalStorageListner = {
on: function(observerKey, eventName, fn) {
subject.subscribe(observerKey, eventName, fn);
},
emit: function(eventName, value, storage) {
storage = storage === 'session' ? window.sessionStorage : window.localStorage;
storage.setItem(eventName, value);
}
};
window.addEventListener('storage', function(event) {
subject.notify(event.key, event.newValue);
});
}
}
export default vueTabEvents
if (typeof window !== 'undefined' && window.Vue) {
window.Vue.use(vueTabEvents)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment