【经验总结】简陋无比的观察者模式实现
说明:观察者模式超级简陋版,代码很简单
主要实现代码如下:
//简单的工具对象,实现了观察者模式所需的基本要素 var publisher = { whateverType: 'any', subscribers:{ //'any': [] //当不指定订阅类型时,统统扔到这个默认的队列里去 }, //订阅事件,type:事件类型,handler:事件处理方法 subscribe: function(type, handler){ type = type || whateverType; if(typeof this.subscribers[type]==='undefined'){ this.subscribers[type] = []; } this.subscribers[type].push(handler); }, //停止订阅事件,type:事件类型,[handler]:事件处理方法(如不传,则将类型为type的事件订阅队列清空) unsubscribe: function(type, handler){ type = type || whateverType; var subscribers = this.subscribers[type] || []; for(var i=0; i<subscribers.length; i++){ if(!handler || subscribers[i]===handler){ subscribers.splice(i, 1); i--; } } }, //发布事件,type:事件类型,[param]:事件参数,格式可自行定义 publish: function(type, param){ type = type || whateverType; var subscribers = this.subscribers[type] || []; for(var i=0,len=subscribers.length; i<len; i++){ subscribers[i](param); } } };
接下来随便写两个对象,一个做发布者,一个做订阅者吧(一下子想到了老师给学生布置作业神马的。。。)
//工具函数,将source对象的属性拷贝到target里 function extend(target, source){ for( var key in source) target[key] = source[key]; } //仁慈的老师 var Teacher = {}; extend(Teacher, publisher); //听话的学生 var Student = { doHomework: function(){ console.log('homework, i wanna die'); }, takeExam: function(param){ console.log('just '+ param.week_left +' weeks before final exams ! wtf'); } };
简单的测试用例,非详细:
Teacher.subscribe('homework', Student.doHomework); Teacher.subscribe('exam', Student.takeExam); Teacher.publish('homework'); //homework, i wanna die Teacher.publish('exam', {week_left: 2}); //just 2 weeks before final exams ! wtf Teacher.unsubscribe('homework', Student.doHomework); Teacher.publish('homework'); Teacher.publish('exam', {week_left: 2}); //just 2 weeks before final exams ! wtf
观察者模式的简陋实现,代码很简单,思路也不复杂,根据需要稍加修改应该就可以用到实际项目中去,对于项目模块的通信、解耦都有很大作用...省略n字...
github博客:https://github.com/chyingp/blog
新浪微博:http://weibo.com/chyingp
站酷主页:http://www.zcool.com.cn/u/346408/