Created
October 18, 2020 23:38
-
-
Save thlemercier/af156f86f6fb09c8cbf97a7a1f291472 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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