Javascript观察者(发布者-订阅者)模式

自制了一个简单的发布者-订阅者模式的javascript示例, 欢迎大家批评指正.

 1 <script type="text/javascript">
 2 
 3     if (typeof studio == "undefined") {
 4         var studio = studio || {};
 5     };
 6 
 7     studio.editor = {
 8         onClickSubscribers: [],
 9         onFocusSubscribers: [],
10         addSubscriber: function (pub, func) {
11             switch (pub) {
12                 case "onClick":
13                     if (!this.duplicatedSubscriberCheck(this.onClickSubscribers, func)) {
14                         this.onClickSubscribers.push(func);
15                     }
16                     break;
17                 case "onFocus":
18                     if (!this.duplicatedSubscriberCheck(this.onFocusSubscribers, func)) {
19                         this.onFocusSubscribers.push(func);
20                     }
21                     break;
22                 default:
23                     break;
24             }
25         },
26         duplicatedSubscriberCheck: function (subscribers, func) {
27             var isExist = false;
28             for (var i = 0, len = subscribers.length; i < len; i++) {
29                 if (subscribers[i] == func) {
30                     isExist = true;
31                     break;
32                 }
33             }
34             return isExist;
35         },
36         onClick: function () {
37             for (var i = 0, len = studio.editor.onClickSubscribers.length; i < len; i++) {
38                 var s = studio.editor.onClickSubscribers[i];
39                 s(i);
40             }
41             console.log('onClick');
42         },
43         onFocus: function () {
44             for (var i = 0, len = studio.editor.onFocusSubscribers.length; i < len; i++) {
45                 var s = studio.editor.onFocusSubscribers[i];
46                 s(i);
47             }
48             console.log('onFocus');
49         }
50     };
51 
52     function test1(id) {
53         console.log('test1 is called and id=' + id);
54     }
55     function test2(id) {
56         console.log('test2 is called and id=' + id);
57     }
58     studio.editor.addSubscriber("onClick", test1);
59     //test2 is added twice, but will be called only once cuz we have an already-exist-check
60     studio.editor.addSubscriber("onClick", test2);
61     studio.editor.addSubscriber("onClick", test2);
62     studio.editor.onClick();
63 
64     function test3() {
65         console.log('test3 is called');
66     }
67     function test4() {
68         console.log('test4 is called');
69     }
70     studio.editor.addSubscriber("onFocus", test3);
71     studio.editor.addSubscriber("onFocus", test4);
72     studio.editor.onFocus();
73 </script>

 

posted @ 2016-03-11 09:57  RC7  阅读(264)  评论(0编辑  收藏  举报