1

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?

2 Answers 2

1

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...
}
Sign up to request clarification or add additional context in comments.

2 Comments

The immediately invoked function is not needed here as there is no iteration with shared variables going on.
@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.
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.