Last active
September 10, 2019 16:42
-
-
Save sketchpunk/3f6d6ecc26307beaff55171b5890b41e to your computer and use it in GitHub Desktop.
Event manager and Callback Manager
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
class Callbacks{ | |
constructor(){ | |
this.cb = {}; | |
} | |
on( eName, func ){ | |
if( !this.cb[ eName ] ) this.cb[ eName ] = new Array(); | |
this.cb[ eName ].push( func ); | |
return this; | |
} | |
off( eName, func ){ | |
let idx = this.cb[ eName ].indexOf( func ); | |
if( idx !== -1 ) this.cb[ eName ].splice( idx, 1 ); | |
return this; | |
} | |
offAll( eName ){ | |
let ary = this.cb[ eName ]; | |
if( !ary ) console.error( "Callbacks.offAll : Event Name Not Found ", eName ); | |
else ary.length = 0; | |
return this; | |
} | |
count( eName ){ return ( this.cb[ eName ] )? this.cb[ eName ].length : 0; } | |
// emit( name, detail) | |
emit( eName, data=null ){ | |
if( this.count( eName ) ){ | |
let f; | |
for( f of this.cb[ eName ] ){ | |
try{ | |
f( data ); | |
}catch( err ){ | |
console.error("Callback.emit ", eName, " : ", err ); | |
} | |
} | |
} | |
return this; | |
} | |
} | |
export default Callbacks; |
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
class EventManager{ | |
constructor(){ | |
this.elm = document.createElement("i"); | |
this.events = {}; | |
} | |
on( eName, func ){ | |
this.elm.addEventListener( eName, func ); | |
if( !this.events[ eName ] ) this.events[ eName ] = new Array(); | |
this.events[ eName ].push( func ); | |
return this; | |
} | |
off( eName, func ){ | |
this.elm.removeEventListener( eName, func ); | |
let idx = this.events[ eName ].indexOf( func ); | |
if( idx !== -1 ) this.events[ eName ].splice( idx, 1 ); | |
return this; | |
} | |
off_all( eName ){ | |
let ary = this.events[ eName ]; | |
if( !ary ) console.error( "EventManager.off_all : Event Name Not Found ", eName ); | |
else{ | |
let func; | |
for( func of ary ) this.elm.removeEventListener( eName, func ); | |
} | |
return this; | |
} | |
emit( eName, detail=null ){ | |
this.elm.dispatchEvent( new CustomEvent( eName, { detail, bubbles:true, cancelable:true, composed:false } ) ); | |
return this; | |
} | |
} | |
export default EventManager; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment