JS 观察者模式

Events = function() {

var listen, log, obj, one, remove, trigger, __this;
obj = {};
__this = this;

listen = function(key, eventfn) { //把简历扔盒子, key就是联系方式.
var stack; //stack是盒子
stack = obj[key] != null ? obj[key] : obj[key] = [];
return stack.push(eventfn);
};

one = function(key, eventfn) {
remove(key);
return listen(key, eventfn);
};

remove = function(key) {
return obj[key] != null ? obj[key].length = 0 : void (0);
};

trigger = function() { //面试官打电话通知面试者
var fn, stack, i, len, key;
key = Array.prototype.shift.call(arguments);
stack = obj[key] != null ? obj[key] : obj[key] = [];
for (i = 0, len = stack.length; fn=stack[i++];) {
if (fn.apply(__this, arguments) === false) {
return false;
}
}
}
return {
listen: listen,
one: one,
remove: remove,
trigger: trigger
}


}


var adultTv = Events();

adultTv.listen('play', function(data) {
alert("whose file will show today " + data.name);
});

//发布者
adultTv.trigger('play', {
'name': 'david'
})

posted @ 2013-06-21 18:14  mguo  阅读(1883)  评论(0编辑  收藏  举报