js实现观察者模式
来源:互联网 发布:安藤忠雄中山邸数据 编辑:程序博客网 时间:2024/05/16 11:43
var publisher = {subscribers: {any: [] // event type: subscribers},subscribe: function (fn, type) {type = type || 'any';if (typeof this.subscribers[type] === "undefined") {this.subscribers[type] = [];}this.subscribers[type].push(fn);},unsubscribe: function (fn, type) {this.visitSubscribers('unsubscribe', fn, type);},publish: function (publication, type) {this.visitSubscribers('publish', publication, type);},visitSubscribers: function (action, arg, type) {var pubtype = type || 'any',subscribers = this.subscribers[pubtype],i,max = subscribers.length;for (i = 0; i < max; i += 1) {if (action === 'publish') {subscribers[i](arg);} else {if (subscribers[i] === arg) {subscribers.splice(i, 1);}}}}};function makePublisher(o) {var i;for (i in publisher) {if (publisher.hasOwnProperty(i) && typeof publisher[i] === "function") {o[i] = publisher[i];}}o.subscribers = {any: []};}var paper = {daily: function () {this.publish("big news today");},monthly: function () {this.publish("interesting analysis", "monthly");}};makePublisher(paper);var joe = {drinkCoffee: function (paper) {console.log('Just read ' + paper);},sundayPreNap: function (monthly) {console.log('About to fall asleep reading this ' + monthly);}};paper.subscribe(joe.drinkCoffee);paper.subscribe(joe.sundayPreNap, 'monthly');paper.daily();paper.daily();paper.daily();paper.monthly();
0 0
- JS实现观察者模式
- js实现观察者模式
- js实现观察者模式
- js观察者模式简单实现
- 事件机制 -- 典型观察者模式 js实现
- js实现观察者模式风格替换
- PHP设计模式之JS实现观察者模式
- js观察者模式
- js观察者模式
- js观察者模式
- js观察者模式2
- js观察者模式
- JS观察者模式
- js观察者模式
- js观察者模式
- 【JS】观察者模式
- js观察者模式
- js设计模式-观察者模式
- POJ 3126 Prime Path
- C++new申请内存后的判断和assert()
- Chromium的当前net/disk_cache/simple file模块没有实现缓存的原子更新
- Oracle-1:的列操作(增加列,修改列,删除列),包括操作多列
- 插入排序
- js实现观察者模式
- Geekband STL与泛型编程 第三周笔记 暗影行者
- 4Sum
- PHP md5
- android app 打包问题,jar文件的重复很头疼
- Android SwitchCompat 自定义颜色 及使用
- leetcode 19. Remove Nth Node From End of List
- 推荐算法——基于图的推荐算法PersonalRank算法
- tolua学习资料汇总贴