Denis
Denis

Reputation: 2469

Return result after deferred execution in jQuery plugin without callback function?

I have plugin, which has return direction (like: top, left..) of which side you enter the element. The problem is - one function inside plugin executed after some timeout, so when i call plugin - obviously it return me undefined.

;(function($){
  jQuery.fn.myplugin = function(options){

    var somefunction = function(){
        setTimeout(function(elem, e){
            return elem * e; // some action, no matter
        }, 500)              // the important thing - it's executed after plugin returned undefined
    }

    return someFunction;

  };
})(jQuery);

Is it possible to resolve this without using callback function, or it is necessary in this case?

I'd like to user plugin like

var direction = $('elem').myplugin();

but with callback this should be

$('elem').myplugin({
    callback: function(direction){
        // so i got direction here
    }
})

looks not so pretty anymore

Upvotes: 0

Views: 126

Answers (2)

calebds
calebds

Reputation: 26228

You cannot get around using a callback function, that is the nature of setTimeout and asynchronous programming in general. It is a good thing, do not be deterred if it does not seem as "pretty".

But in the way of prettiness, there is no need to define the callback inside the plugin call:

// "driver" code
$('elem').myplugin({
  callback: myApplicationCallback //or desired name
});

// your application logic code
function myApplicationCallback(direction) {
  // do work
}

clean!

Upvotes: 2

CodePB
CodePB

Reputation: 1756

Your function is asynchronous, so your code does not know when your function completes, and cannot wait till the end of the execution of your function. Therefore it is not possible to wait for the code to complete and return the result.

To avoid the requirement of a callback function, you will have to avoid asynchronous code (avoid setTimeout). Otherwise, you will need a callback function

Upvotes: 2

Related Questions