3-10 unique的设计
本节编程练习不计算学习进度,请电脑登录imooc.com操作

unique的设计

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

 

任务

  1. <!DOCTYPE HTML>
  2. <html>
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  5. <script src="http://img1.sycdn.imooc.com//down/540812440001e40e00000000.js" type="text/javascript"></script>
  6. <script src="http://img1.sycdn.imooc.com//down/541f6ff70001a0a500000000.js" type="text/javascript"></script>
  7. <title></title>
  8. </head>
  9. <body>
  10.  
  11. <script type="text/javascript">
  12.  
  13.  
  14. function Callbacks(options) {
  15. var list = [];
  16. var self;
  17. var firingStart;
  18. var memory;
  19.  
  20. function _fire(data) {
  21. memory = options === 'memory' && data;
  22. firingIndex = firingStart || 0;
  23. firingStart = 0;
  24. firingLength = list.length;
  25. for (; list && firingIndex < firingLength; firingIndex++) {
  26. list[firingIndex](data)
  27. }
  28. }
  29.  
  30. self = {
  31. add: function(fn) {
  32. var start = list.length;
  33. if (options == 'unique') {
  34. if (-1 === list.indexOf(fn)) {
  35. list.push(fn)
  36. }
  37. } else {
  38. list.push(fn)
  39. }
  40. if (memory) {
  41. firingStart = start; //获取最后一值
  42. _fire(memory);
  43. }
  44. },
  45. fire: function(args) {
  46. if (list) {
  47. _fire(args)
  48. }
  49. }
  50. }
  51. return self;
  52. }
  53.  
  54.  
  55. function fn1(val) {
  56. show('fn1 says ' + val);
  57. }
  58. var callbacks = Callbacks( "unique" );
  59. callbacks.add( fn1 );
  60. callbacks.add( fn1 ); // 重复添加
  61. callbacks.add( fn1 );
  62. callbacks.fire( "foo" );
  63.  
  64.  
  65.  
  66. </script>
  67.  
  68. </body>
  69. </html>
下一节