代码示例

    1. class EventHub{
    2. constructor(){
    3. this.events = {}
    4. }
    5. on(type,handle){
    6. this.events[type] = (this.events[type] || [] ).concat(handle)
    7. }
    8. emit(type,data){
    9. this.events[type].forEach(handle=>handle(data))
    10. }
    11. off(type,handle){
    12. if(!this.events[type]) return
    13. if(!handle){
    14. delete this.events[type]
    15. return
    16. }
    17. let index = this.events[type].indexOf(fn)
    18. if (index===-1) return
    19. this.events[type].splice(index,1)
    20. }
    21. }

    测试代码

    1. let eventHub = new EventHub()
    2. let fn1 = ()=>{console.log(1)}
    3. let fn2 = ()=>{console.log(2)}
    4. let fn3 = ()=>{console.log(3)}
    5. let fn4 = ()=>{console.log(4)}
    6. let fn5 = ()=>{console.log(5)}
    7. eventHub.on('event',fn1)
    8. eventHub.on('event',fn2)
    9. eventHub.on('event',fn3)
    10. eventHub.on('event',fn4)
    11. eventHub.on('event',fn5)
    12. eventHub.emit('event')
    13. eventHub.off('event',fn2)

    「@浪里淘沙的小法师」