1

I've a set interval function like this -

setInterval(function(){ 
     var postData = {'some json data'};

     var successCallback = function(data) {
           console.log(data);
     }

     var errorCallback = function(data) {
          console.log(data);
     }

     RestClient.invokeRemoteService(postData, this.successCallback, this.errorCallback);

}, 10000);

And Here is my invokeRemoteService() method at of RestClient (at another file) -

RestClient = window.RestClient || {};

(function (w, rs) {
    rs.invokeRemoteService = function ( postData, successCallBack, errorCallBack){ //label-1, successCallback and errorCallback are undefined

            $.ajax({
                url : '/some/url/',
                dataType : "json",
                data :{
                    cmd: ko.toJSON(postData)
                },
                type : "post",
                async : true,

                success : function(data) { //label-2, get data ok
                    if (typeof successCallBack === "function") { //label-3, successCallBack is undefined
                        successCallBack(data); //label-4
                    }
                },
                error : function() {
                    if (typeof errorCallBack === "function") {
                        errorCallBack(); //label-5
                    }
                }

            });

    };
})(window, RestClient);

But when I call RestClient.invokeRemoteService() method from setInterval() method I always get 'undefined' for successCallback and errorCallback at label-1, label-3 and label-5. Though the service call done perfectly and I get correct data at label-2. TheRestClient.invokeRemoteService()work fine for other. But when I call it fromsetInterval()` its not working. Please help.

Razib
  • 10,057
  • 10
  • 46
  • 71

1 Answers1

2

No need for this, your successCallback and errorCallback are directly in the scope.

setInterval(function(){ 
     var postData = {'some json data'};

     var successCallback = function(data) {
           console.log(data);
     }

     var errorCallback = function(data) {
          console.log(data);
     }

     RestClient.invokeRemoteService(postData, successCallback, errorCallback);

}, 10000);
ghybs
  • 34,277
  • 5
  • 51
  • 73
  • Thanks it works!. But since I'm new to javascript, I can't understand why it was not working when I used 'this'.Can you kindly please explain a bit. – Razib Oct 22 '17 at 19:36
  • 1
    `this` is used to access the function caller _context_. Most of the time it is the global context (`window`), and in case the function is an object method, that object instance. In your case, you are trying to refer to variables in a _scope_ / _closure_, which is done directly without using `this`. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this and https://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work – ghybs Oct 22 '17 at 19:41