Summary of JS callback function

Keywords: Programming JQuery

What is a callback function?

In computer programming, call back function, or call back for short, refers to the reference of a piece of executable code passed to other code by function parameters.

This design allows the underlying code to call subroutines defined at a higher level.
Quoted from Wikipedia

Programming falls into two categories: system programming and application programming. The so-called system programming, in short, is to write libraries; and application programming is to use a variety of libraries written to write programs with a certain function, that is, applications. System programmers will leave some interfaces for their libraries, namely API (application programming interface), to be used by application programmers.
So in the abstraction layer diagram, libraries are at the bottom of the application.
When a program runs, the application program usually calls the pre-prepared functions in the library through the API. But some library function s require the application to pass a function to it first, so that it can be called at the right time to accomplish the target task. The function that is passed in and then called is called a callback function.

Author: Bridgehead
Links: https://www.zhihu.com/question/19801131/answer/27459821
Source: Know
Copyright belongs to the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

Raise a chestnut.

When you go to a store to buy something, you just don't have what you want, so you leave your phone number with the shop assistant. After a few days, the shop assistant calls you, and then you pick up the goods in the shop. In this example, your phone number is called callback function, you leave the phone to the clerk and call the registration callback function. Later, there is an event called triggering the callback correlation in the store. The clerk calls you to call the callback function, and you go to the store to pick up the goods is called the response callback event.

Author: Chang Xiling
Links: https://www.zhihu.com/question/19801131/answer/13005983
Source: Know
Copyright belongs to the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.

jQuery medium

jQuery Callback function

The Callback function is executed after 100% of the current animation is completed.

for example

$(selector).hide(speed,callback)

Raise a chestnut.

The sample code part comes from the jQuery API

$("button").click(function(){
$("p").hide(1000);
});

Error (no callback)

$("p").hide(1000);
alert("The paragraph is now hidden");

//alert pops up before hide is over

Correct (with callback)

$("p").hide(1000,function(){
alert("The paragraph is now hidden");
});

Callbacks is a method introduced by jQuery 1.7

A multipurpose callback list object that manages a set of callback functions with the same method parameters

Callbacks() provides jQuery's. ajax() and $. Deferred() basic functional components internally. It can be used as a function of a new component similar to the underlying definition.

jQueryjQuery.callbacks(flags)

function fn1( value ){
    console.log( value );
}

function fn2( value ){
    fn1("fn2 says:" + value);
    return false;
}

var callbacks = $.Callbacks();
callbacks.add( fn1 );
callbacks.fire( "foo!" ); // outputs: foo!

callbacks.add( fn2 );
callbacks.fire( "bar!" ); // outputs: bar!, fn2 says: bar!

As a result, it makes it easy to construct complex callback lists, and input values can be easily used as many functions as needed.

- callbacks.add(callbacks) // Add a collection of callbacks or callbacks
- callbacks.remove(callbacks)//Delete the collection of callbacks or callback lists

callbacks: A function, or an array of functions, is used to add to the callback list.

- callbacks.fire(arguments) // Call all callbacks with a given parameter

arguments: This parameter or parameter list is returned to the callback list

var callbacks = $.Callbacks();
callbacks.add( fn1 );
callbacks.fire( "foo!" ); // outputs: foo!

callbacks.add( fn2 );
callbacks.fire( "bar!" ); // outputs: bar!, fn2 says: bar!

callbacks.remove(fn2);
callbacks.fire( "foobar" ); 

// only outputs foobar, as fn2 has been removed.

Flags

An optional parameter, structured as an optional list of markers separated by space markers, that changes the behavior in the callback list

Available flags:

Once: Make sure that this callback list is executed only once (like a deferred Deferred).
Memor: Keep the previous value and the latest value to be added to the back of this list and immediately execute any callbacks (like a deferred Deferred).
unique: Make sure that only one callback can be added at a time (so there is no duplication in the list).
stopOnFalse: Interrupts the call when a callback returns false
//$.Callbacks( 'once' ):
var callbacks = $.Callbacks( "once" );
callbacks.add( fn1 );
callbacks.fire( "foo" );
callbacks.add( fn2 );
callbacks.fire( "bar" );
callbacks.remove( fn2 );
callbacks.fire( "foobar" );

/*
output: 
foo
*/

//$.Callbacks( 'memory' ):

var callbacks = $.Callbacks( "memory" );
callbacks.add( fn1 );
callbacks.fire( "foo" );
callbacks.add( fn2 );
callbacks.fire( "bar" );
callbacks.remove( fn2 );
callbacks.fire( "foobar" );

/*
output:
foo
fn2 says:foo
bar
fn2 says:bar
foobar
*/

//$.Callbacks( 'unique' ):

var callbacks = $.Callbacks( "unique" );
callbacks.add( fn1 );
callbacks.fire( "foo" );
callbacks.add( fn1 ); // repeat addition
callbacks.add( fn2 );
callbacks.fire( "bar" );
callbacks.remove( fn2 );
callbacks.fire( "foobar" );

/*
output:
foo
bar
fn2 says:bar
foobar
*/

$.Callbacks( 'stopOnFalse' ):

function fn1( value ){
    console.log( value );
    return false;
}

function fn2( value ){
    fn1("fn2 says:" + value);
    return false;
}

var callbacks = $.Callbacks( "stopOnFalse");
callbacks.add( fn1 );
callbacks.fire( "foo" );
callbacks.add( fn2 );
callbacks.fire( "bar" );
callbacks.remove( fn2 );
callbacks.fire( "foobar" );

/*
output:
foo
bar
foobar
*/

$.Callbacks( 'unique memory' ):

function fn1( value ){
    console.log( value );
    return false;
}

function fn2( value ){
    fn1("fn2 says:" + value);
    return false;
}

var callbacks = $.Callbacks( "unique memory" );
callbacks.add( fn1 );
callbacks.fire( "foo" );
callbacks.add( fn1 ); // repeat addition
callbacks.add( fn2 );
callbacks.fire( "bar" );
callbacks.add( fn2 );
callbacks.fire( "baz" );
callbacks.remove( fn2 );
callbacks.fire( "foobar" );

/*
output:
foo
fn2 says:foo
bar
fn2 says:bar
baz
fn2 says:baz
foobar
*/

Flag combines are used. Callbacks() internal. done() and. fail() a deferred container they all use. Callbacks('memory once').

The $. Callbacks method can also be separated, and for convenience there should be a short version that needs to be defined:

var callbacks = $.Callbacks(),
add = callbacks.add,
remove = callbacks.remove,
fire = callbacks.fire;

add( fn1 );
fire( "hello world");
remove( fn1 );

Then the method is introduced.

callbacks.disable()

No parameters, disable callbacks in the callback list

callbacks.empty()

Without parameters, delete all callbacks from the list

callbacks.fired()

The bool value itself is returned if the callback in the list is called back to true at least once or false otherwise

callbacks.fireWith([context][,args])

context: context references triggered by callbacks in this list

args: A parameter or parameter list is returned to the callback list.

When fire is called, we add this in the function to point to our Callbacks instance, for example

var cb = $.Callbacks();

cb.add(function () {
    console.log(this === cb);
});

cb.fire();//true

fireWith is to change the context of the function we add, that is, this points to, for example

var cb = $.Callbacks();

var obj = {
    name: 'objName'
};

cb.add(function (age) {
    console.log(this.name, age);
});

cb.fireWith(obj, [26]);//objName 26

fireWith's first parameter is our context, and the second parameter is the content array we need to pass. Note that it's an array!

callbacks.has(callbacks)

callbacks: callbacks for Search

// a sample logging function to be added to a callbacks list
var foo = function( value1, value2 ){
    console.log( 'Received:' + value1 + ',' + value2 );
}

// a second function which will not be added to the list
var bar = function( value1, value2 ){
    console.log( 'foobar');
}

var callbacks = $.Callbacks();

// add the log method to the callbacks list
callbacks.add( foo );

// determine which callbacks are in the list

console.log( callbacks.has( foo ) ); // true
console.log( callbacks.has( bar ) ); // false
callbacks.lock()

Lock a callback list in its current state

// a sample logging function to be added to a callbacks list
var foo = function( value ){
    console.log( 'foo:' + value);
}

var callbacks = $.Callbacks();

// add the logging function to the callback list
callbacks.add( foo );

// fire the items on the list, passing an argument
callbacks.fire( 'hello' );
// outputs 'foo: hello'

// lock the callbacks list
callbacks.lock();

// try firing the items again
callbacks.fire( 'world' );

// as the list was locked, no items
// were called so 'world' isn't logged
callbacks.locked()

Determine whether the list of callbacks has been locked, as in fired()

$.Callbacks, $.Deferred and Pub/Sub

The general idea behind pub / sub (Observer mode) is to promote loose coupling of applications. A single object, an object, rather than a specific task or activity of another object, is invoked against a method of another object, and is notified when it occurs. Observers are also known as subscribers, and we refer to publishers (or principals) who observe them. Notify Users of Publisher Events

As a component. Callbacks() creativity, it can implement a pub/sub system using only callback lists. Using. Callbacks as a topic queue, a publishing and subscribing topic system can be implemented as follows:

var topics = {};

jQuery.Topic = function( id ) {
    var callbacks,
        method,
        topic = id && topics[ id ];
    if ( !topic ) {
        callbacks = jQuery.Callbacks();
        topic = {
            publish: callbacks.fire,
            subscribe: callbacks.add,
            unsubscribe: callbacks.remove
        };
        if ( id ) {
            topics[ id ] = topic;
        }
    }
    return topic;
};

Then, it is easy to use the publishing and subscribing events of interest for this part of the application:

// Subscribers
$.Topic( "mailArrived" ).subscribe( fn1 );
$.Topic( "mailArrived" ).subscribe( fn2 );
$.Topic( "mailSent" ).subscribe( fn1 );

// Publisher
$.Topic( "mailArrived" ).publish( "hello world!" );
$.Topic( "mailSent" ).publish( "woo! mail!" );

// Here, "hello world!" gets pushed to fn1 and fn2
// when the "mailArrived" notification is published
// with "woo! mail!" also being pushed to fn1 when
// the "mailSent" notification is published. 

/*
output:
hello world!
fn2 says: hello world!
woo! mail!
*/

Although this is useful, further implementation can be taken. Using $. Deferreds, this is possible to ensure that the publisher only publishes a notification that a particular task has been completed (resolved) for the user. This may be some further comments on how to use them in practice, see the following code example:

// subscribe to the mailArrived notification
$.Topic( "mailArrived" ).subscribe( fn1 );

// create a new instance of Deferreds
var dfd = $.Deferred();

// define a new topic (without directly publishing)
var topic = $.Topic( "mailArrived" );

// when the deferred has been resolved, publish a 
// notification to subscribers
dfd.done( topic.publish );

// Here the Deferred is being resolved with a message
// that will be passed back to subscribers. It's possible to
// easily integrate this into a more complex routine
// (eg. waiting on an ajax call to complete) so that
// messages are only published once the task has actually
// finished.
dfd.resolve( "its been published!" );

Posted by sumitnice@rediffmail.com on Wed, 10 Apr 2019 23:42:31 -0700