//1.事件驱动改造方案
//2.回调列表功能增强
//3.状态管理模式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script src="stateAdmin.js"> </script>
<script>
var callbackList = _.callbackList('once memory');
callbackList.add(function(){
console.log('aaa')
});
callbackList.add(function(){
console.log('bbb')
});
callbackList.fire()
</script>
</body>
</html>
(function(root){
var optionsCache = {};
var spaceExp = /\s+/;
var _ = {
callbackList: function(options){
options = typeof options === 'string'? (optionsCache[options] || createOptions(options)): {};
var list = [];
var index, length, memory, start, testing;
var fire = function(data){
memory = options.memory && data;
index = start || 0;
start = 0;
testing = true;
length = list.length;
for(; index < length; index++){
if(list[index].apply(data[0], data[1]) === false && options.stopOnfalse){
break;
}
}
}
var self = {
add: function(){
var args = Array.prototype.slice.call(arguments);
start = list.length;
args.forEach(function(fn){
if(toString.call(fn) === "[object Function]") {
list.push(fn)
}
})
memory && fire(memory);
return this;
},
fireWith: function(context, arguments){ //处理函数的绑定上下文对象
var args = [context, arguments]
if(!options.once || !testing){
fire(args);
}
},
fire: function(){ //状态绑定参数的传递
self.fireWith(this, arguments)
}
}
return self;
}
};
function createOptions(options){
var object = optionsCache[options] = {};
options.split(spaceExp).forEach(function(value){
object[value] = true;
});
return object;
}
root._ = _;
})(this);