自己动手实现jQuery Callbacks完整功能代码详解

2020-05-18 08:43:17易采站长站整理

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.


利用Callbacks 实现发布订阅模式 pub/sub: (官方文档)



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


使用



$.Topic( ‘mailArrived’ ).subscribe( function ( e )
        {
            console.log( ‘Your have new email! ‘ );