Create custom callbacks

I have a page with some jQuery and a separate function other than jQuery.

My function currently works on $ (document) .ready, but I want to call the jQuery function as soon as my function is complete. I can pass my function as a callback to any jQuery function, but how can I configure everything the other way around?

Therefore, I would like to know how to create a foo function that will take care of this for me:

$(document).ready(function() {
  foo(myfunction(), $(bar).something);
}

or how to extend an existing function to handle callbacks. Thanks.

+3
source share
3 answers

() , javascript call() () , . , this ( ) apply. Call() apply() , .

function myfunction(callback) {
    // do stuff
    if (callback) 
        callback.apply(this);
}
+6

, , , ... .

- :

var add = function(a, b){
    return a+b;
};

, :

var add = function(a, b, callback){
    callback();
    return a+b;
};

( , )

+2

:

Function.prototype.appendCallback = function(callback){
  var fn = this;
  return function(){
    fn.apply( this, arguments ); // execute original function
    callback.call(this);         // then the callback
  };
};

:

var newConfirm = window.confirm.appendCallback(function () {
  alert('after from callback');
});

newConfirm('hello?'); // shows a confirmation, and then executes the callback.
+2

Source: https://habr.com/ru/post/1715908/


All Articles