Set callback function inside javascript class

Sorry pseudo code, my actual file is much larger: /

I want to call a function (with parameters) inside a class. However, this function must be passed to the class as a variable.

someObject = {
    itWorked:function(answer){
       alert(answer);
    },

    plugins:{
        somePlugin:function(){

            var callback;
            this.doSomething = doSomething;

            function setCallback(c){
                callback = c;
            }

            function doSomething(){
                 var answer = "hello";
                 [callback](answer); // how do I call this?
            }

        }
    },

    widgets:{
        something:function(){
            var doIt = new someObject();
            doIt.setCallback(someObject.itWorked()); // how do I send this?
            doIt.doSomething();
        }
    }
}

So, how would you pass a class itWorked()to a class? And how would I call this function itWorked(answer)inside the class, and also pass the variable if?

+5
source share
2 answers

Remove parentheses to pass the function as a variable.

doIt.setCallback( someObject.itWorked );

Then you can use the callback like any other function.

callback( answer );
+1
source

You will need to change

setCallback = function (c) {callback = c;}

to

this.setCallback =  function (c) {callback = c;}

therefore, the setCallback function will be publicly available.

, :

callback.call(scope, param1, param2);

, :

callback.apply(scope, parameters);

Scope , {}, .

, , javascript. javascript-,

var mynamespace = {};

(function () {
   function MyObject(param1, param2) {
      this.initialize(param1, param2);
   }

   MyObject.prototype = {
      initialize: function (param1, param2) {
          var privateScope = {
              param1: param1,
              param2: param2,
              callback: null
          };

          this.setCallback = function (c) {
              privateScope.callback = c;
          }

          this.doSomething = function () {
              if (privateScope.callback) {
                  privateScope.callback.call();
              }
          }
      }
   }
   mynamespace.MyObject = MyObject;
}());

,

var obj = new mynamespace.MyObject("value1", "value2");
+3

All Articles