首页 > 代码库 > JQuery源码解析(十)

JQuery源码解析(十)

默认回调对象设计

不传入任何参数,调用add的时候将函数add到内部的list中,调用fire的时候顺序触发list中的回调函数:

function fn1(val) {
  console.log(‘fn1 says:‘ + val);
}

function fn2(val) {
  console.log(‘fn2 says ‘ + val);
}
var cbs = $.Callbacks();
cbs.add(fn1);
cbs.fire(‘foo‘);
console.log(‘........‘)
cbs.add(fn2);
cbs.fire(‘bar‘)

 结果就是按照顺序叠加触发,如下列表:

  

fn1 says:foo 
………………………
fn1 says:bar 
fn2 says bar

 这种就是最简单的处理了,可以直接模拟,代码如下:

function Callbacks() {
  var list = [];
  var self;
  self = {
    add: function(fn) {
      list.push(fn)
    },
    fire: function(args) {
      list.forEach(function(fn) {
        fn(args);
      })
    }
  }
  return self;
}

 代码:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="http://img.mukewang.com/down/540812440001e40e00000000.js" type="text/javascript"></script>
<script src="http://img.mukewang.com/down/541f6ff70001a0a500000000.js" type="text/javascript"></script>

<title></title>
</head>
<body>

<script type="text/javascript">


function Callbacks() {
  var list = [];
  var self;
  self = {
    add: function(fn) {
      list.push(fn)
    },
    fire: function(args) {
      list.forEach(function(fn) {
        fn(args);
      })
    }
  }
  return self;
}

function fn1(val) {
  show(‘fn1 says:‘ + val);
}
function fn2(val) {
  show(‘fn2 says ‘ + val);
}

var cbs = Callbacks();
cbs.add(fn1);
cbs.fire(‘foo‘);
cbs.add(fn2);
cbs.fire(‘bar‘)



</script>

</body>
</html>

 

JQuery源码解析(十)