首页 > 解决方案 > 回调函数的自定义参数取决于事件

问题描述

我怎样才能像这样自定义回调函数的参数:

//THIS IS AN EXAMPLE
object = {
  x : 20,
  y : 10,
  on : (event,callback)=>{
    //What staff can i do here 
    //to costumize my callback parameters depending of the event
    //wich i can exploit this parameter later
    //like $.on('click',function(param)) on jQuery 
  }
};

object.on('send',(param)=>{
  //and here depending of event='send' this variable param 
  //is returned by the other definition of "object"..
});

我可以在这里做什么工作人员来自定义我的回调参数具体取决于事件女巫我以后可以像$.on('click',function(param))在 jQuery 上一样利用这个参数。

如果有什么不清楚的请问我。

提前致谢 :)

标签: javascriptfunctionparameterscallbackparameter-passing

解决方案


这就是我的意思,我解决了我的问题,谢谢:

object = {
  x : 20,
  y : 10,
  on : function(event,callback){
    switch(event){
      case 'get' : callback({'x':this.x,'y':this.y});break;
      case 'multiple': callback(this.x*this.y);break;
      case 'addition': callback(this.x+this.y);break;
      default : callback('No event passed');
    }
  }
};

object.on('get',(param)=>{
  console.log(param);//Object { x: 20, y: 10 }
});

推荐阅读