Last active
December 3, 2021 05:52
-
-
Save YankeeTube/647567e7e2cafbcd431221910203add4 to your computer and use it in GitHub Desktop.
It easily helps listeners of dirty events in Specific Elements. I was inspired by Vue.js' Watch.
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
const EventWatch = function(selector, instance, config={}) { | |
this.subscribe = {[selector]: {}} | |
this.selector = selector | |
this.element = document.querySelector(selector) | |
if (!this.element) throw "Element Not found." | |
Object.entries(instance).map(([eventName, eventHandler]) => { | |
const newEventHandler = (e) => { | |
const beforeEvent = new CustomEvent(`${eventName}:before`) | |
const afterEvent = new CustomEvent(`${eventName}:after`) | |
this.element.dispatchEvent(beforeEvent) | |
eventHandler.call(this.element, e) | |
this.element.dispatchEvent(afterEvent) | |
} | |
this.element.removeEventListener(eventName, newEventHandler, config) | |
this.element.addEventListener(eventName, newEventHandler, config) | |
this.subscribe = {[selector]: {...this.subscribe[selector], [eventName]: eventHandler}} | |
}) | |
this.unSubscribe = function(targetEventName=null) { | |
if (targetEventName) { | |
const hanlder = this.subscribe[selector][targetEventName] | |
this.element.removeEventListener(targetEventName, hanlder) | |
delete this.subscribe[selector][targetEventName] | |
} else { | |
Object.entries(this.subscribe[selector]).map(([eventName, eventHandler]) => { | |
this.element.removeEventListener(eventName, eventHandler) | |
}) | |
} | |
} | |
window.eventWatchList = Object.freeze({ | |
...window?.eventWatch, | |
...this.subscribe, | |
}) | |
} | |
export default EventWatch |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Event Watcher
this script is anti-framework. or anti-library
I was inspired by
Vue.js
Watch. So Simple Event Management Script.About
Event Watcher
I prefer vanilla js, but I was so dissatisfied that the code of vanilla controlling DOM was quite long.
In addition, as
element.addEventlistener('event',func)
increased, it was noticeable that the code itself became dirty, and I thought it would be good to split the file for each element if it was managed like Vue.js watcher.jsSo, the ultimate goal was to write a short code and make it possible to develop it even if Vanilla JS was used.
I'm not sure if it's actually true, but at least the Element declaration has decreased, so it seems to be so dog honey.
Usage
Function
Arrow Function
Before / After
need to original Event!.
Get All Event Subscribe
Get
selector
Event SubscribeEvent
selector
All unSubscribeEvent
selector
specific unSubscribe