Eduardo Ponce de Leon
Eduardo Ponce de Leon

Reputation: 9696

How to pass a value from a jquery plugin to its callback function

I created a simple Jquery function that takes a few parameters and comes up with some kind of result. I need to be able to pass this result to the call Back function of the jquery plugin.

(function( $ ){
   $.fn.newPlugin= function(params,CBfunction){

    //do some stuff;
    var result = "something";
    CBfunction.call(this);

}; 
})( jQuery );

when I use the plugin I want to be able to parse the result of the plugin to the callback function:

$(elm).newPlugin(params, function(params, this.result){
  //this.resullt comes from the plugin ('something');

})

Is this possible?

For example look at the variable "myVar":

(function( $ ){
   $.fn.newPlugin= function(a,b,CBfunction){

    myVar = a+b;

    CBfunction.call(this);

}; 
})( jQuery );

I use the plugin:

$(elm).newPlugin(a,b,function(){
  alert("the result of "+a+" + "+b+" is:"+myVar);
})

myVar comes from the plugin and used in the callback function, is there any way to do this?

Thanks.

Upvotes: 0

Views: 171

Answers (1)

Rafid
Rafid

Reputation: 20189

Why not just pass the result when you call the callback? Like this:

(function( $ ){
   $.fn.newPlugin= function(params,CBfunction){

    //do some stuff;
    var result = "something";
    CBfunction.call(this, result);
};
})(jQuery);

Then you need to modify your call to look like this (by the way, notice that I removed the 'param' parameter form the callback, because only one parameter is being passed):

$(elm).newPlugin(params, function(result){
  // result comes from the plugin ('something');
})

Upvotes: 2

Related Questions