<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>观察模式例子</title>
</head>
<body>
</body>
<script type="text/javascript">
var Events = function() {
var obj = {};
obj.stack=[];
var listen = function( key, eventfn ) { //事件消息队列
var stack = obj[key] ? obj[key] : (obj[ key ] = []);//1.在obj对象上添加盒子属性;2.用三目运算符解决拓展问题
return stack.push(eventfn);
};
var one = function( key, eventfn ) {//添加一个唯一的订阅
remove( key );
return listen( key, eventfn );
};
var remove = function( key ) {
return obj[key] ? obj[key].length = 0 : void 0; //取消订阅
};
var trigger = function() { //面试官打电话通知面试者
var fn, stack, key;
key = Array.prototype.shift.call( arguments );//获取arguments参数数组的第一个值
stack = obj[key] ? obj[key] : obj[key] = [];
for ( var i = 0,len = stack.length; i < len; i++ ) {
fn = stack[i];
if (fn)
{
fn.apply(this,arguments);
}
}
}
return {
listen: listen,
one: one,
remove: remove,
trigger: trigger
}
}
//订阅者
var adultTv = Events();
adultTv.listen( 'play',(data)=> {return alert("今天是谁的电影:" + data.name)})
//发布者
adultTv.trigger('play',{'name': "刘德华"});
</script>
</html>