Created
December 27, 2013 06:11
-
-
Save MrPeak/8143232 to your computer and use it in GitHub Desktop.
Observer pattern.( Based on JavaScript object )
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 观察者模式 | |
| var observer = { | |
| addSubscriber: function (callback) { | |
| this.subscribers[this.subscribers.length] = callback; | |
| }, | |
| removeSubscriber: function (callback) { | |
| var len = this.subscribers.length, | |
| i; | |
| for (i = 0; i < len - 1; i++) { | |
| if (this.subscribers[i] === callback) { | |
| this.subscribers.splice(i, 1); | |
| } | |
| } | |
| }, | |
| publish: function (what) { | |
| var len = this.subscribers.length, | |
| i; | |
| for (i = 0; i < len; i++) { | |
| if (typeof this.subscribers[i] === "function") { | |
| this.subscribers[i](what); | |
| } | |
| } | |
| }, | |
| make: function (o) { | |
| var i; | |
| for (i in this) { | |
| o[i] = this[i]; | |
| } | |
| o.subscribers = []; | |
| console.warn('发布者注册完毕') | |
| } | |
| }; | |
| // 注册发布者 | |
| var tonightPaper = { | |
| newIssue: function () { | |
| var paper = "Have a wonderful love !"; | |
| this.publish(paper); | |
| } | |
| }; | |
| observer.make(tonightPaper); | |
| // 注册订阅者 | |
| var glue = { | |
| read: function (what) { | |
| console.warn("It says" + what); | |
| } | |
| }; | |
| tonightPaper.addSubscriber(glue.read); | |
| tonightPaper.newIssue(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment