0

So I have this function

$.fn.myFunction = function( options, callback ) {
    var settings = $.extend({
        opacity     : '',
        margin  : ''
    }, options );
}

and I do some funny stuff like this

$('.selector').myFunction( options, function() { /* do some stuff */ } );

Where should I specify inside my function about the callback function and how?

2 Answers 2

1

Like this :

JS

$.fn.myFunction = function( options , callback ) {
    var settings = $.extend({
        opacity     : '',
        margin  : ''
    }, options );

    // where you want your callback
    if(callback && typeof callback === "function") callback();
}
Sign up to request clarification or add additional context in comments.

3 Comments

It's weird because it works fine for me : jsfiddle.net/OxyDesign/2ua11u6y Can you send a jsfiddle to show your problem ? Thanks
You can also add your callback as a method of your options object and invoke it like this if(options.callback && typeof options.callback === "function") options.callback();
Thanks guys, I managed, I had to put the callback() inside the .onComplete() of another function.
1

A callback is simply a parameter in a function. So, your case could be expressed very simply:

var myFunction = function(options, callback) {
    console.log('I am running in the main function');
    if (callback) { callback(); }
};

myFunction('', function() {
    console.log('I am running in the callback!');
});

Demo is here: http://repl.it/0b0

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.