您的位置:首页 > 其它

初学es6写了个观察者模式,请多指教!!!!

2017-07-19 10:48 190 查看
/**
* Created by richard on 2017/7/19.
*/
console.log("------------observer观察者模式-------------");
class Observer{
constructor(){
this.handle = [];//相关订阅fn
}
addSubscribe(topic,fn){
this.handle.push({topic:topic,fn:fn});
console.log(this.handle);
}
removeSubscribe(topic,fn) {
let index ;
this.handle.forEach(function (data,i) {
if(data.topic==topic&&data.fn==fn){
index=i;
}
});
delete this.handle[index];
console.log(this.handle);
}
publish(topic,message){
this.handle.forEach(function(data){
if(data.topic==topic){
data.fn(message);
}
});
}
}
{
let test = new Observer();
let fn1 = function(data){
console.log(data);
}
let fn2 = function(data){
console.log("I'm in fn2 say "+data);
}
test.addSubscribe('abc',fn1);
test.addSubscribe('abc',fn2);
test.addSubscribe('abcd',fn2);
test.publish('abc','hello');
test.publish('abcd','good job');
test.removeSubscribe('abc',fn2);
test.publish('abc','fn2 you are here?')
}
console.log("--------------------------------------");
学习网址:http://www.cnblogs.com/TomXu/archive/2012/03/02/2355128.html 特此感谢!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: