event-utility
v0.0.3
Published
An utility for handling events
Downloads
3
Readme
event-utility
A utility for easily managing events
Installation
$ npm install --save event-utility
Usage
Adding and removing events
const EventManager = require("event-utility");
const eventManager = new EventManager();
const id = eventManager.addEvent(target, eventName, callback);
eventManager.removeEvent(target, eventName, callback);
// or
eventManager.removeEventById(id);
Examples
const id1 = eventManager.addEvent(window, "click", () => {
console.log("hi 1");
});
const id2 = eventManager.addEvent(window, "click", () => {
console.log("hi 2");
});
eventManager.removeEventById(id1);
When window's click event is fired it will output "hi 2"
function sayHi() {
console.log("hi");
}
eventManager.addEvent(window, "click", sayHi);
eventManager.removeEvent(window, "click", sayHi);
When window's click event is fired it will not have logged anything
Advance removing events
const props = {
target?,
eventName?,
callback?,
};
eventManager.clearAll(props?);
If not prop specified it will remove all events added with that eventManager
instance.
Otherwise it will remove all events that match every one of the params.
Examples
eventManager.addEvent(document.body, "click", () => {
console.log("will not");
});
eventManager.addEvent(window, "click", () => {
console.log("click");
});
eventManager.clearAll({
target: document.body,
});
Here it should log only "click"
eventManager.addEvent(window, "keyup", () => {
console.log("keyup");
});
eventManager.addEvent(window, "click", () => {
console.log("click");
});
eventManager.clearAll({
eventName: "click",
});
Clicking will not log anything. Typing keys will do instead
eventManager.addEvent(document.body, "keyup", () => {
console.log("keyup");
});
eventManager.addEvent(document.body, "click", () => {
console.log("click body");
});
eventManager.addEvent(window, "click", () => {
console.log("click window");
});
eventManager.clearAll({
target: document.body,
eventName: "click",
});
Here it will log "click window" and "keyup".