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

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

输出:


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).