Simply declare the callback as one of the parameters to your function, and
call it when you're ready.

Let's take a non-jQuery example for simplicity.

    // Call a callback function after a random delay of 1 to 5 seconds,
    // and pass the time delay we used as an argument to the callback
    function randomDelay( callback ) {
        var time = Math.floor( Math.random() * 4000 + 1000 );
        setTimeout( function() {
            callback( time );
        }, time );
    }

    // Test it
    randomDelay( function( time ) {
        alert( 'Delayed ' + time + ' milliseconds' );
    });

If you need to specify what 'this' will be inside the callback, you can use
.call() or .apply() when you call it. Otherwise you can just call it
directly.

For your jQuery plugin function, it would look something like this:

    $.fn.myFunction = function( argument, options, callback ) {
        // ... prepare someData and then ...
        callback( someData );
        // ...
    };

Note that the name 'callback' is not magic; it's just an argument name. You
might call it 'ready' or whatever you like.

-Mike

On Sat, Oct 10, 2009 at 11:09 AM, kknaru <isai...@gmail.com> wrote:

>
> hi there, how can i write a function that accepts a callback
> function?
>
> $(selector).myFunction(argument,options,function(){
>               //do the thing
> });
>
> i want myFunction to load some data via(an unordored list actually)
> load method end then somehow to return the wrapped elements for the
> callback function, exactly like load() does.
>

Reply via email to