1

i am very new in jquery. so i was searching google for jquery callback function and i got a code but i did not understand the flow of the code. so please anyone help me to understand the coding flow.

here is the code

function mightyplugin(foo, callback){
// big code block here

   callback.apply(this, [foo]);
}

mightyplugin("Bar!", function(param){
    alert(param);
});

here i am passing "Bar!" as one argument to function mightyplugin and a anonymous function.

  1. what callback.apply does. what this keyword will hold actually.... why it is required.
  2. why [foo] is passed as array.
  3. what would be the syntax if i pass many argument like

    mightyplugin("Bar!","1stone","2ndone", function(param){
        alert(param);
    });
    

i know callback function invoke when first function finish but here situation is different... why?

please explain...
thanks

James Montagne
  • 73,502
  • 13
  • 107
  • 127
Keith Costa
  • 1,713
  • 11
  • 35
  • 63

2 Answers2

1

First of all, this isn't jquery. This is an example of how to deal with callback functions yourself, independent of jquery.

To answer your qestions:

  1. Details on apply can be found here: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/apply
  2. As you'll see if you read the above link, the 2nd parameter passed to apply is an array of arguments.
  3. I'm not sure what your intent is for those other parameters, but you can simply add more parameters to your function:

function mightyplugin(foo, foo1, foo2, callback){
   // big code block here

   callback.apply(this, [foo, foo1, foo2]);
}

mightyplugin("Bar!","1stone","2ndone", function(param){ alert(param); });
James Montagne
  • 73,502
  • 13
  • 107
  • 127
  • some time i saw callback function is invoke like callback.call(this, [foo, foo1, foo2]); instead of callback.apply(this, [foo, foo1, foo2]); .so i need to know what is the difference between apply & call. when to use call() and when to use apply(). plzz put some focus. thanks. – Keith Costa Nov 03 '11 at 19:39
  • http://stackoverflow.com/questions/1986896/what-is-the-difference-between-call-and-apply – James Montagne Nov 03 '11 at 20:20
1
  1. this is the current function context, in your situation mightyplugin
  2. foo is passed as an array because apply needs an array as argument
  3. mightyplugin([1,2,3,4], function(){...});
    and then callback.apply(this, foo)

You can read more on the Mozilla Developer Network on apply and it's brother call

topek
  • 17,226
  • 3
  • 33
  • 43