Create a custom callback in JavaScript

前端 未结 10 2281
野性不改
野性不改 2020-11-22 08:08

All I need to do is to execute a callback function when my current function execution ends.

function LoadData() 
{
    alert(\'The data has been loaded\');
          


        
10条回答
  •  醉梦人生
    2020-11-22 09:01

    If you want to execute a function when something is done. One of a good solution is to listen to events. For example, I'll implement a Dispatcher, a DispatcherEvent class with ES6,then:

    let Notification = new Dispatcher()
    Notification.on('Load data success', loadSuccessCallback)
    
    const loadSuccessCallback = (data) =>{
       ...
    }
    //trigger a event whenever you got data by
    Notification.dispatch('Load data success')
    

    Dispatcher:

    class Dispatcher{
      constructor(){
        this.events = {}
      }
    
      dispatch(eventName, data){
        const event = this.events[eventName]
        if(event){
          event.fire(data)
        }
      }
    
      //start listen event
      on(eventName, callback){
        let event = this.events[eventName]
        if(!event){
          event = new DispatcherEvent(eventName)
          this.events[eventName] = event
        }
        event.registerCallback(callback)
      }
    
      //stop listen event
      off(eventName, callback){
        const event = this.events[eventName]
        if(event){
          delete this.events[eventName]
        }
      }
    }
    

    DispatcherEvent:

    class DispatcherEvent{
      constructor(eventName){
        this.eventName = eventName
        this.callbacks = []
      }
    
      registerCallback(callback){
        this.callbacks.push(callback)
      }
    
      fire(data){
        this.callbacks.forEach((callback=>{
          callback(data)
        }))
      }
    }
    

    Happy coding!

    p/s: My code is missing handle some error exceptions

提交回复
热议问题