Unique:确保一次只能添加一个回调(所以在列表中没有重复的回调)
function fn1(val) { console.log('fn1 says ' + val); } var callbacks = $.Callbacks( "unique" ); callbacks.add( fn1 ); callbacks.add( fn1 ); // repeat addition callbacks.add( fn1 ); callbacks.fire( "foo" );
结果:过滤了相同的add操作
fn1 says foo
过滤重复的比较简单,因为是数组的保存方式,我们可以在入口处通过indexOf判断即可
function Callbacks(options) { var list = []; var self; var firingStart; var memory; function _fire(data) { memory = options === 'memory' && data; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; for (; list && firingIndex < firingLength; firingIndex++) { list[firingIndex](data) } } self = { add: function(fn) { var start = list.length; if (options == 'unique') { if (-1 === list.indexOf(fn)) { list.push(fn) } } else { list.push(fn) } if (memory) { firingStart = start; //获取最后一值 _fire(memory); } }, fire: function(args) { if (list) { _fire(args) } } } return self; }
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script src="http://img1.sycdn.imooc.com//down/540812440001e40e00000000.js" type="text/javascript"></script> <script src="http://img1.sycdn.imooc.com//down/541f6ff70001a0a500000000.js" type="text/javascript"></script> <title></title> </head> <body> <script type="text/javascript"> function Callbacks(options) { var list = []; var self; var firingStart; var memory; function _fire(data) { memory = options === 'memory' && data; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; for (; list && firingIndex < firingLength; firingIndex++) { list[firingIndex](data) } } self = { add: function(fn) { var start = list.length; if (options == 'unique') { if (-1 === list.indexOf(fn)) { list.push(fn) } } else { list.push(fn) } if (memory) { firingStart = start; //获取最后一值 _fire(memory); } }, fire: function(args) { if (list) { _fire(args) } } } return self; } function fn1(val) { show('fn1 says ' + val); } var callbacks = Callbacks( "unique" ); callbacks.add( fn1 ); callbacks.add( fn1 ); // 重复添加 callbacks.add( fn1 ); callbacks.fire( "foo" ); </script> </body> </html>