ingd
ingd

Reputation: 119

Javascript: add function as parameter to predefined callback function

I have this code that uses a cordov/phonegap plugin:

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
    }
  
}

Now sensors.getState has one argument and is predefined by plugin . I would like to execute a function passed as added argument like: sensor.getState(app.callback(firstFunction)) or when i need sensor.getState(app.callback(secondFunction))

Thanks. IngD

Upvotes: 0

Views: 83

Answers (1)

Frog
Frog

Reputation: 124

Try this

    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();

Upvotes: 1

Related Questions