How to refactor this Javascript anonymous function?

Posted by HeavyWave on Stack Overflow See other posts from Stack Overflow or by HeavyWave
Published on 2010-03-30T00:48:31Z Indexed on 2010/03/30 0:53 UTC
Read the original article Hit count: 515

Filed under:
|

We have this anonymous function in our code, which is part of the jQuery's Ajax object parameters and which uses some variables from the function it is called from.

this.invoke = function(method, data, callback, error, bare) {
      $.ajax({
        success: function(res) {
            if (!callback) return;

            var result = "";
            if (res != null && res.length != 0)
                var result = JSON2.parse(res);

            if (bare)
            { callback(result); return; }

            for (var property in result) {
                callback(result[property]);
                break;
            }
        }
   });
}

I have omitted the extra code, but you get the idea. The code works perfectly fine, but it leaks 4 Kbs on each call in IE, so I want to refactor it to turn the anonymous function into a named one, like this.onSuccess = function(res) { .. }.

The problem is that this function uses variables from this.invoke(..), so I cannot just take it outside of its body. How do I correctly refactor this code, so that it does not use anonymous functions and parent function variables?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery