Search code examples
javascriptjquerycallbackargumentsdata-transfer

how to add additional argument to getJson callback for non anonymous function?


I have following working code:

newParam=1;
$.getJSON('http://date.jsontest.com/', (function (x) {
    return function (data) {
      alert(x);     
    }}(newParam)));

newParam=2;

demo

I want to make internal function non anonymous. but I cannot:

newParam=1;
$.getJSON('http://date.jsontest.com/', (function (x) {
    return func ;}(newParam)));

newParam=2;

function func(data) {
      alert(x);     
    }

message: x is not defined

Please help to refactor this code.


Solution

  • If you want the inner function to have access to the outer function's scope (in this case, the x argument), you need the inner to actually be declared in the outer, like this:

    newParam=1;
    $.getJSON('http://date.jsontest.com/', funcFactory(newParam));
    
    function funcFactory(x) {
      return function func(data) {
          alert(x);     
      };
    }
    

    Or you can modify your second example to use .bind() as suggested by dfsq but with some tweaks - use it to set the this object but not the arguments (because jQuery will set the arguments when it calls it with the result of the JSON request):

    newParam=1;
    $.getJSON('http://date.jsontest.com/', function (x) {
        return func.bind({param: x});
    }(newParam));
    
    newParam=2;
    
    function func(data) {
       alert(this.param);   // note use of this
       alert(data);     
    }
    

    Demo: http://jsfiddle.net/x0eqpv6f/11/

    Although if you're going to use .bind() you don't need the anonymous function at all:

    $.getJSON('http://date.jsontest.com/', func.bind({param: newParam}));
    
    function func(data) {
       alert(this.param); // note use of this
       alert(data);     
    }
    

    Demo: http://jsfiddle.net/x0eqpv6f/12/