File size: 2,230 Bytes
08aee07 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | 'use strict';
class EventPubSub {
constructor( scope ) {
this._events_ = {};
this.publish = this.trigger = this.emit;
this.subscribe = this.on;
this.unSubscribe = this.off;
}
on( type, handler, once ) {
if ( !handler ) {
throw new ReferenceError( 'handler not defined.' );
}
if ( !this._events_[ type ] ) {
this._events_[ type ] = [];
}
if(once){
handler._once_ = once;
}
this._events_[ type ].push( handler );
return this;
}
once( type, handler ) {
return this.on( type, handler, true );
}
off( type, handler ) {
if ( !this._events_[ type ] ) {
return this;
}
if ( !handler ) {
throw new ReferenceError( 'handler not defined. if you wish to remove all handlers from the event please pass "*" as the handler' );
}
if ( handler == '*' ) {
delete this._events_[ type ];
return this;
}
const handlers = this._events_[ type ];
while ( handlers.includes( handler ) ) {
handlers.splice(
handlers.indexOf( handler ),
1
);
}
if ( handlers.length < 1 ) {
delete this._events_[ type ];
}
return this;
}
emit( type, ...args ) {
if ( !this._events_[ type ] ) {
return this.emit$( type, ...args );
}
const handlers = this._events_[ type ];
const onceHandled=[];
for ( let handler of handlers ) {
handler.apply( this, args );
if(handler._once_){
onceHandled.push(handler);
}
}
for(let handler of onceHandled){
this.off(type,handler);
}
return this.emit$( type, ...args );
}
emit$( type, ...args ) {
if ( !this._events_[ '*' ] ) {
return this;
}
const catchAll = this._events_[ '*' ];
for ( let handler of catchAll ) {
handler.call( this, type, ...args );
}
return this;
}
}
module.exports = EventPubSub;
|