jsはイベント処理を実現し、購読者モードを実現する.
696 ワード
class event {
construct(){
this.event = {};
}
function once(eventName, cb) = {
this.on(eventName,(...args) => {
cb(...args);
this.off(eventName);
});
}
function emit(eventName, ...args) {
if(this.event.hasOwnPropety(eventName)){
for(let cb of this.event[eventName]){
cb(...args);
}
}
}
function on(eventName, cb) {
if (!this.event.hasOwnPropety(eventName)){
this.event[eventName] = [];
}
this.event[eventName].push(cb);
}
function off(eventName) {
delete this.event[eventName];
}
}