@etsoo/react
Version:
TypeScript ReactJs UI Independent Framework
42 lines (41 loc) • 1.02 kB
JavaScript
/**
* Event watcher
*/
export class EventWatcher {
constructor() {
this.actions = [];
}
/**
* Add action
* @param action Action
*/
add(action) {
this.actions.push(action);
}
/**
* Do the event
* @param event Event
*/
do(event) {
// Type
const type = typeof event === "string" ? event : event.type;
// Execute
const removeIndices = [];
this.actions.forEach((item, index) => {
if (!this.isMatch(item, type))
return;
item.action(event);
if (item.once)
removeIndices.push(index);
});
// Remove all once actions
removeIndices.reverse().forEach((index) => this.actions.splice(index, 1));
}
isMatch(action, type) {
if (action.type == null)
return true;
if (typeof action.type === "string")
return action.type === type;
return action.type.includes(type);
}
}