Pass an extra argument to a callback function

后端 未结 4 1532
陌清茗
陌清茗 2020-11-22 03:09

I have a function callWithMagic which takes a callback function as a parameter and calls it with one argument.

const callWithMagic = callback =&         


        
相关标签:
4条回答
  • 2020-11-22 03:56

    You can bind argument object to callback function:

    var varObject = {var1: "findButton", var2: true};
    
    function cbFunc() {
        console.log(this.var1+ ":" + this.var2);
    }
    
    //Example callback
    datatable.ajax.reload(cbFunc.bind(varObject));
    
    0 讨论(0)
  • You could use an anonymus function

    something like

    session.sub('Hello', function(){marketEvents(your args);});
    
    0 讨论(0)
  • 2020-11-22 03:58

    You can create a function which calls the marketEvent function. No need to complicate things

    session.sub('Hello', function(args, kwargs) {
        marketEvent(args, kwargs, 'my custom data');
    });
    

    otherwise you can do this:

    var mrktEvent = function(customArgs) {
        return function(args, kwargs) { 
            marketEvent(args, kwargs, customArgs) 
        };
    }
    
    session.sub('Hello', mrktEvent("customEvent"));
    
    0 讨论(0)
  • 2020-11-22 04:03

    Just create a wrapper callback:

    callWithMagic(function(magic) {
      return processMagic(magic, 42);
    });
    

    Or using ECMAScript 6 arrow functions:

    callWithMagic(magic => processMagic(magic, 42));
    
    0 讨论(0)
提交回复
热议问题