Create a custom callback in JavaScript

前端 未结 10 2181
野性不改
野性不改 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

    My 2 cent. Same but different...

    <script>
        dosomething("blaha", function(){
            alert("Yay just like jQuery callbacks!");
        });
    
    
        function dosomething(damsg, callback){
            alert(damsg);
            if(typeof callback == "function") 
            callback();
        }
    </script>
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-22 09:02
    function LoadData(callback) 
    {
        alert('the data have been loaded');
        callback(loadedData, currentObject);
    }
    
    0 讨论(0)
  • 2020-11-22 09:03

    Try:

    function LoadData (callback)
    {
        // ... Process whatever data
        callback (loadedData, currentObject);
    }
    

    Functions are first class in JavaScript; you can just pass them around.

    0 讨论(0)
提交回复
热议问题