Javascript:将函数作为参数添加到预定义的回调函数中

时间:2016-10-17 09:27:15

标签: javascript

我有这个使用cordov / phonegap插件的代码:



var app = { 
   init: function (){
     sensors.getState(app.callback);
   },
   callback: function(state){
     //parameter of this callback function is define by cordova plugin 
     if (state[0] == 0) {
       //execute another function passed as argument because I wwant to change it in other parts of my code
       }
   },
   firstFunction(){
     //execute action 1
     },
   secondFunction(){
    //execute action 2
    }
  
}




现在sensors.getState有一个参数,由插件预定义。我想执行一个作为添加参数传递的函数,如:  sensor.getState(app.callback(firstFunction))或当我需要sensor.getState(app.callback(secondFunction))

感谢。 IngD

1 个答案:

答案 0 :(得分:1)

试试这个

    var app = {
    init: function() {
        sensors.getState(app.callback);
    },
    test: function() {},
    setCallback: function(callback) {
        app.test = callback;
    },
    callback: function(state) {
        app.test();
    },
    firstFunction() {
        alert("firstFunction");
    },
    secondFunction() {
        alert("secondFunction");
    }
};
app.setCallback(app.firstFunction);
app.callback();
app.setCallback(function () { alert("thirdFunction"); });
app.callback();