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

用法和$.Callbacks完全一致 , 但是只是实现了add , remove , fire , empty, has和带参数的构造函数功能,  $.Callbacks 还有disable,disabled, fireWith , fired , lock, locked 方法

 代码如下:

 

复制代码 代码如下:

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

 测试函数如下:(注意fn1 fn2是匿名函数, fn2返回false , fn3是有“名”函数)

 

复制代码 代码如下:

 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 . 测试add & fire

var cb=new MyCallbacks();

cb.add(fn1)

cb.add(fn2)

cb.add(fn3)

cb.fire('hello')

输出:

fn1 hello
fn2 hello
fn3 hello

2.测试remove
var cb=new MyCallbacks();

cb.add(fn1)

cb.add(fn2)

cb.add(fn3)

cb.remove(fn1)
cb.fire('hello')
cb.remove(fn3)
cb.fire('hello')
输出:

fn1 hello
fn2 hello
fn3 hello
----------------------------
fn1 hello
fn2 hello

2.测试has
var cb=new MyCallbacks();

cb.add(fn1)

cb.add(fn2)

cb.add(fn3)

cb.has(fn1) 

cb.has(fn3) 

输出:

false

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

true

3.测试带参数的构造函数 : once

var cb=new MyCallbacks('once')

cb.add(fn1)

cb.fire('hello')

cb.fire('hello')

cb.add(fn2)

cb.fire('hello')

输出:

hello

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

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

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

4.测试带参数的构造函数 : memory

 var cb=new MyCallbacks('memory')

cb.add(fn1)

cb.fire('hello') // 输出 : fn1 hello

cb.add(fn2) // 输出 : fn2 hello

cb.fire('hello')

 输出 :

 fn1 hello

 fn2 hello

5.测试带参数的构造函数 : stopOnFalse

var cb=new MyCallbacks('stopOnFalse')

cb.add(fn1)

cb.add(fn2)

cb.add(fn3)

cb.fire('hello')

输出:

fn1 hello
fn2 hello
6.测试带参数的构造函数 :unique

var cb=new MyCallbacks('unique')

 

b.add(fn3)

b.add(fn3)

cb.fire('hello')

输出:

fn3 hello

 

7. 测试带组合参数的构造函数:四个设置参数可以随意组合,一下只测试全部组合的情况, 不然要写16个测试用例 T_T

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

cb.add(fn1) // 输出: fn1

cb.add(fn2) // 输出: fn2

cb.add(fn3) //  输出: fn3

cb.fire('hello')

输出:

fn1 hello
fn2 hello
cb.fire('hello') // 输出:没有输出

 

以下是官方API 文档:

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

构造函数 : 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.

利用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! ' );
            console.log( "mail title : " + e.title );
            console.log( "mail content : " + e.content );
        }
        );

        $.Topic( 'mailArrived' ).publish( { title: 'mail title', content: 'mail content' } );

实现了其余的全部功能 :callbacks.disable , callbacks.disabled,   callbacks.fired,callbacks.fireWith, callbacks.lock, callbacks.locked ,然后重构了下代码结构, 将实现放入了匿名函数内, 然后通过工厂方法 window.callbacks 返回实例,以免每次使用必须 new .

具体代码如下, 有兴趣和时间的可以对照jQuery版本的Callbacks对比下 :

复制代码 代码如下:

( 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 );

时间: 2024-11-27 09:52:54

自己动手实现jQuery Callbacks完整功能代码详解_jquery的相关文章

jQuery实现区域打印功能代码详解_jquery

使用CSS控制打印样式,需要设置样式media="print",并且将页面中不需要打印的元素的样式display属性设置为none.如DEMO中,我将页头页脚及其他不需要打印的元素的样式设置如下: <style type="text/css" media="print"> #header,.top_title,#jqprint,#footer,#cssprint h3{display:none} </style> 用jQu

jQuery fadeOut 异步实例代码详解_jquery

定义和用法 fadeOut() 方法逐渐改变被选元素的不透明度,从可见到隐藏(褪色效果). 注释:隐藏的元素不会被完全显示(不再影响页面的布局). 提示:该方法通常与 fadeIn() 方法一起使用. 语法 $(selector).fadeOut(speed,easing,callback) 1. 概述 jquery实现动画效果的函数使用起来很方便,不过动画执行是异步的,所以要把自定义的操作放在回调函数里. 2. example <html> <body> <table id

jQuery Ajax 全局调用封装实例代码详解_jquery

有一种情况:全站都要用异步方式来调用 数据,提交数据,那么你每次操作 都会要$.ajax({.....}) 写重复的方法 和代码,冗余太大, 也浪费时间,虽说你有代码自动提示补全,但真的不优雅,身为前端极客,是不能允许的! [嘿嘿!虽说我现在基本不用jquery了 ,不过异步概念 是永远要用的,就帮助下新人] jQuery Ajax通用js封装 第一步:引入jQuery库 <script type="text/javascript" src="/js/jquery.mi

jQuery EasyUI菜单与按钮详解_jquery

EasyUI 简介 easyui是一种基于jQuery的用户界面插件集合. easyui为创建现代化,互动,JavaScript应用程序,提供必要的功能. 使用easyui你不需要写很多代码,你只需要通过编写一些简单HTML标记,就可以定义用户界面. easyui是个完美支持HTML5网页的完整框架. easyui节省您网页开发的时间和规模. easyui很简单但功能强大的. 代码如下: <html> <head> <meta http-equiv="Content

TinyMCE汉化及本地上传图片功能实例详解_jquery

TinyMCE我就不多介绍了,这是下载地址:https://www.tinymce.com/download/ 下载下来是英文版,要汉化也很简单. 首先去网上随便下载个汉化包,然后把汉化包解压后的langs文件夹里的zh_CN.js拷到你下载的TinyMCE的langs文件夹中就行.最后在 tinymce.init中加上"language: "zh_CN","(后面会贴出代码) 本地图片上传我用到了Jquery中的uploadify和UI,所以需要引用jquery.

jquery.map()方法的使用详解_jquery

原型方法map跟each类似调用的是同名静态方法,只不过返回来的数据必须经过另一个原型方法pushStack方法处理之后才返回,源码如下: map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, 本文主要就是分析静态map方法至于pushStack在下一篇随笔里面分析: 首先了解下

jQuery AJAX timeout 超时问题详解_jquery

先给大家分析下超时原因: 1.网络不通畅. 2.后台运行比较慢(服务器第一次运行时,容易出现) 超时结果:JQ中 timeout设置请求超时时间. 如果服务器响应时间超过了 设置的时间,则进入 ERROR (错误处理) 超时解决方案: 1.默认的timeout为0,代表永不超时 2.尽量把timeout设置的大一点.坏处:使数据的加载变慢(貌似.呵呵). 3.在ERROR回调函数中写 有关于 超时 处理 的函数:例如,可以在超时的情况下再次调用取数据函数. -------------------

jquery 遍历数组 each 方法详解_jquery

JQuery拿取对象的方式 $('#id') :通过元素的id $('tagName') : 通过元素的标签名 $('tagName tagName') : 通过元素的标签名,eg: $('ul li') $('tagName#id): 通过元素的id和标签名 $(':checkbox'):拿取input的 type为checkbox'的所有元素: Eg: <input type="checkbox" name="appetizers" value="

jQuery unbind 删除绑定事件详解_jquery

unbind([type],[data]) 是 bind()的反向操作,从每一个匹配的元素中删除绑定的事件.如果没有参数,则删除所有绑定的事件.你可以将你用bind()注册的自定义事件取消绑定.如果提供了事件类型作为参数,则只删除该类型的绑定事件.如果把在绑定时传递的处理函数作为第二个参数,则只有这个特定的事件处理函数会被删除. 返回值 : jQuery 参数 : type (String) : (可选) 事件类型 data (Function) : (可选) 要从每个匹配元素的事件中反绑定的事