views:

57

answers:

2

I am trying to write a jQuery plugin, that can be applied to a selector. Within this plugin, there are multiple calls to webservices, where callback methods are required.

The problem I am having is maintaining the current context item in the each loop of the selector.

(function($){
  $.fn.myMethod = function(){

    return this.each(function(){
      var c = $(this);
      $.api.methodToCall("", CallbackFunction);
    });

  };

  function CallbackFunction(data, result){
    // do stuff based on c
  }
})(jQuery);

Normally, you would provide the callback function straight away, which allows me to access c, however within the callback function, there potentially is another api call, so it would start to get messy. Is there any way to do this?

+1  A: 

EDITED

As Sean pointed out, my first edition was a bit more complicated than the situation required...

$.api.methodToCall("", function(data, result) {
    CallbackFunction(data, result, context);
});

function CallbackFunction(data, result, c) {
   // you can access 'c' here...
}

Or, if you prefer

$.api.methodToCall("", function(data, result) {
    CallbackFunction.call(c, data, result);
});

function CallbackFunction(data, result) {
    // you can access 'this' here...
}
David Hedlund
The immediately invoked function is not needed here as there is no iteration with shared variables going on.
Sean Kinsey
@Sean Kinsey: ah, you're right, that was overly complicated. edited. +1'd you, and keeping my examples to illustrate that the callback can be extracted to a separate function (for readability, say), and still have a reference to the context, which i believe was the core of the question.
David Hedlund
+1  A: 

This is the easiest approach

(function($) {
    $.fn.myMethod = function() {
        return this.each(function() {
            var c = $(this);
            $.api.methodToCall("", function() {
                // do stuff based on c
            });
        });
    };
})(jQuery);

Here we bring the callback function into the local scope, and so it has access to c directly.

Sean Kinsey