Self implementation of jQuery Callbacks complete function code details

  • 2020-03-30 00:00:46
  • OfStack

The usage is exactly the same as $.callbacks, but it only implements add, remove, fire, empty, has, and the constructor function with arguments,   Callbacks also have disable,disabled, fireWith, fired, lock, locked methods

  The code is as follows:

 


 String.prototype.trim = function ()
        {
            return this.replace( /^s+|s+$/g, '' );
        };
        // Simulate jQuery.Callbacks object
        function MyCallbacks( options )
        {
            var ops = { once: false, memory: false, unique: false, stopOnFalse: false };
            if ( typeof options === 'string' && options.trim() !== '' )
            {
                var opsArray = options.split( /s+/ );
                for ( var i = 0; i < options.length; i++ )
                {
                    if ( opsArray[i] === 'once' )
                        ops.once = true;
                    else if ( opsArray[i] === 'memory' )
                        ops.memory = true;
                    else if ( opsArray[i] === 'unique' )
                        ops.unique = true;
                    else if ( opsArray[i] === 'stopOnFalse' )
                        ops.stopOnFalse = true;
                }
            }
            var ar = [];
            var lastArgs = null;
            var firedTimes = 0;
            function hasName( name )
            {
                var h = false;
                if ( typeof name === 'string'
                    && name !== null
                    && name.trim() !== ''
                    && ar.length > 0 )
                {
                    for ( var i = 0; i < ar.length; i++ )
                    {
                        if ( ar[i].name === name )
                        {
                            h = true;
                            break;
                        }
                    }
                }
                return h;
            }
            // add a function
            this.add = function ( fn )
            {
                if ( typeof fn === 'function' )
                {
                    if ( ops.unique )
                    {
                        // check whether it had been added before
                        if ( fn.name !== '' && hasName( fn.name ) )
                        {
                            return this;
                        }
                    }
                    ar.push( fn );
                    if ( ops.memory )
                    {
                        // after added , call it immediately
                        fn.call( this, lastArgs );
                    }
                }
                return this;
            };
            // remove a function
            this.remove = function ( fn )
            {
                if ( typeof ( fn ) === 'function'
                    && fn.name !== ''
                    && ar.length > 0 )
                {
                    for ( var i = 0; i < ar.length; i++ )
                    {
                        if ( ar[i].name === fn.name )
                        {
                            ar.splice( i, 1 );
                        }
                    }
                }
                return this;
            };
            // remove all functions 
            this.empty = function ()
            {
                ar.length = 0;
                return this;
            };
            // check whether it includes a specific function
            this.has = function ( fn )
            {
                var f = false;
                if ( typeof ( fn ) === 'function'
                    && fn.name !== ''
                    && ar.length > 0 )
                {
                    for ( var i = 0; i < ar.length; i++ )
                    {
                        if ( ar[i].name === fn.name )
                        {
                            f = true;
                            break;
                        }
                    }
                }
                return f;
            };
            // invoke funtions it includes one by one 
            this.fire = function ( args )
            {
                if ( ops.once && firedTimes > 0 )
                {
                    return this;
                }
                if ( ar.length > 0 )
                {
                    var r;
                    for ( var i = 0; i < ar.length; i++ )
                    {
                        r = ar[i].call( this, args );
                        if ( ops.stopOnFalse && r === false )
                        {
                            break;
                        }
                    }
                }
                firedTimes++;
                if ( ops.memory )
                {
                    lastArgs = args;
                }
                return this;
            };
        };
 

  The test function is as follows :(note that fn1 fn2 is an anonymous function, fn2 returns false, and fn3 is a function with a name)

 


 var fn1 = function ( v )
        {
            console.log( 'fn1 ' + ( v || '' ) );
        };
        var fn2 = function ( v )
        {
            console.log( 'fn2 ' + ( v || '' ) );
            return false;
        };
        function fn3( v )
        {
            console.log( 'fn3 ' + ( v || '' ) );
        };
 

  1. Test add & fire

Var cb = new MyCallbacks ();

Cb. The add (fn1)

Cb. The add (fn2)

Cb. The add (fn3)

Cb. The fire (' hello ')

Output:

Fn1 hello!
Fn2 hello!
Fn3 hello!

2. Test the remove
Var cb = new MyCallbacks ();

Cb. The add (fn1)

Cb. The add (fn2)

Cb. The add (fn3)

Cb. Remove (fn1)
Cb. The fire (' hello ')
Cb. Remove (fn3)
Cb. The fire (' hello ')
Output:

Fn1 hello!
Fn2 hello!
Fn3 hello!
----------------------------
Fn1 hello!
Fn2 hello!

2. The test has
Var cb = new MyCallbacks ();

Cb. The add (fn1)

Cb. The add (fn2)

Cb. The add (fn3)

Cb. From the (fn1)  

Cb. From the (fn3)  

Output:

false

---------------

True,

3. Test the constructor with an argument: once

Var cb = new MyCallbacks (' once ')

Cb. The add (fn1)

Cb. The fire (' hello ')

Cb. The fire (' hello ')

Cb. The add (fn2)

Cb. The fire (' hello ')

Output:

Hello!

-------------------

------------------

------------------------------

4. Test constructor with argument: memory

  Var cb = new MyCallbacks (' memory ')

Cb. The add (fn1)

Cb. Fire ('hello') // output: fn1 hello

Cb. Add (fn2) // output: fn2 hello

Cb. The fire (' hello ')

  Output:

  Fn1 hello!

  Fn2 hello!

5. Test constructor with arguments: stopOnFalse

Var cb = new MyCallbacks (' stopOnFalse)

Cb. The add (fn1)

Cb. The add (fn2)

Cb. The add (fn3)

Cb. The fire (' hello ')

Output:

Fn1 hello!
Fn2 hello!
6. Test the constructor with a parameter :unique

Var cb = new MyCallbacks (' unique ')

 

B.a dd (fn3)

B.a dd (fn3)

Cb. The fire (' hello ')

Output:

Fn3 hello!

 

7. Test the constructor with the combination parameters: the four set parameters can be combined at will, and only all of them can be tested at once; otherwise, 16 test cases T_T will be written

Var cb=new MyCallbacks('once memory unique stopOnFalse')

Cb.add (fn1) // output: fn1

Cb. Add (fn2) // output: fn2

Cb. The add (fn3) / /   Output: fn3

Cb. The fire (' hello ')

Output:

Fn1 hello!
Fn2 hello!
Cb. Fire ('hello') // output: no output

 

Here is the official API documentation:

Description: A multi - purpose callbacks list object that provides A powerful way to manage The callback lists. The $. Callbacks () function is internally, informs The to dojo.provide The base functionality behind The jQuery $. Ajax () And $. Deferred () components. It can be 2 as a similar base to define functionality for new components.

Constructor: jQuery.Callbacks(flags)

flags
Type: String
An optional list of space - separated flags that change how the callback list behaves.
Possible flags:
Once: Ensures the callback list can only be fired once (like a Deferred).
Memory: Keeps track of previous values and will call any callback added after the list has been fired right away with the latest "memorized" values (like a Deferred).
Unique: Ensures a callback can only be added once, so there are no duplicates in the list).
StopOnFalse: Interrupts callings when a callback returns false.
By default a callback list will act like an event callback list and can be "fired" multiple times.

Two specific methods were being used above: Add () and. Fire (). The. Add () method supports adding new callbacks to The callback list, While the. Fire () method executes the added functions and provides a way to pass arguments to be processed by the callbacks in the same list.

Pub /sub with Callbacks: (official document)


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;
        };

use


$.Topic( 'mailArrived' ).subscribe( function ( e )
        {
            console.log( 'Your have new email! ' );
            console.log( "mail title : " + e.title );
            console.log( "mail content : " + e.content );
        }
        );
        $.Topic( 'mailArrived' ).publish( { title: 'mail title', content: 'mail content' } );


All of the remaining functions are implemented: callbacks. Disable, callbacks. Disabled,& disable;   Callbacks. Fired, callbacks. FireWith callbacks. Lock, callbacks. Locked, and then reconstruct the code structure, will realize in the anonymous function, and then through the window. The factory method callbacks returns instance, lest each use must be new.

The specific code is as follows. Those who are interested and have time can compare with the Callbacks in jQuery version:


( function ( window, undefined )
        {
            // Simulate jQuery.Callbacks object
            function Callbacks( options )
            {
                var ops = { once: false, memory: false, unique: false, stopOnFalse: false },
                    ar = [],
                    lastArgs = null,
                    firedTimes = 0,
                    _disabled = false,
                    _locked = false;
                if ( typeof options === 'string' && options.trim() !== '' )
                {
                    var opsArray = options.split( /s+/ );
                    for ( var i = 0; i < options.length; i++ )
                    {
                        if ( opsArray[i] === 'once' )
                            ops.once = true;
                        else if ( opsArray[i] === 'memory' )
                            ops.memory = true;
                        else if ( opsArray[i] === 'unique' )
                            ops.unique = true;
                        else if ( opsArray[i] === 'stopOnFalse' )
                            ops.stopOnFalse = true;
                    }
                }
                function hasName( name )
                {
                    var h = false;
                    if ( typeof name === 'string'
                        && name !== null
                        && name.trim() !== ''
                        && ar.length > 0 )
                    {
                        for ( var i = 0; i < ar.length; i++ )
                        {
                            if ( ar[i].name === name )
                            {
                                h = true;
                                break;
                            }
                        }
                    }
                    return h;
                }
                // add a function
                this.add = function ( fn )
                {
                    if ( typeof fn === 'function' )
                    {
                        if ( ops.unique )
                        {
                            // check whether it had been added before
                            if ( fn.name !== '' && hasName( fn.name ) )
                            {
                                return this;
                            }
                        }
                        ar.push( fn );
                        if ( ops.memory )
                        {
                            // after added , call it immediately
                            fn.call( this, lastArgs );
                        }
                    }
                    return this;
                };
                // remove a function
                this.remove = function ( fn )
                {
                    if ( typeof ( fn ) === 'function'
                        && fn.name !== ''
                        && ar.length > 0 )
                    {
                        for ( var i = 0; i < ar.length; i++ )
                        {
                            if ( ar[i].name === fn.name )
                            {
                                ar.splice( i, 1 );
                            }
                        }
                    }
                    return this;
                };
                // remove all functions 
                this.empty = function ()
                {
                    ar.length = 0;
                    return this;
                };
                // check whether it includes a specific function
                this.has = function ( fn )
                {
                    var f = false;
                    if ( typeof ( fn ) === 'function'
                        && fn.name !== ''
                        && ar.length > 0 )
                    {
                        for ( var i = 0; i < ar.length; i++ )
                        {
                            if ( ar[i].name === fn.name )
                            {
                                f = true;
                                break;
                            }
                        }
                    }
                    return f;
                };
                this.disable = function ()
                {
                    _disabled = true;
                    return this;
                };
                this.disabled = function ()
                {
                    return _disabled;
                };
                this.fired = function ()
                {
                    return firedTimes > 0;
                };
                function _fire( context, args )
                {
                    if ( _disabled || ops.once && firedTimes > 0 || _locked )
                    {
                        return;
                    }
                    if ( ar.length > 0 )
                    {
                        var r;
                        for ( var i = 0; i < ar.length; i++ )
                        {
                            r = ar[i].call( context, args );
                            if ( ops.stopOnFalse && r === false )
                            {
                                break;
                            }
                        }
                    }
                    firedTimes++;
                    if ( ops.memory )
                    {
                        lastArgs = args;
                    }
                };
                this.fireWith = function ( context, args )
                {
                    context = context || this;
                    _fire( context, args );
                    return this;
                };
                this.fire = function ( args )
                {
                    _fire( this, args );
                    return this;
                };
                this.lock = function ()
                {
                    _locked = true;
                    return this;
                };
                this.locked = function ()
                {
                    return _locked;
                };
            };
            // exposed to global as a factory method
            window.callbacks = function ( options )
            {
                return new Callbacks( options );
            };
        } )( window );


Related articles: