1 | <!DOCTYPE html>
|
2 | <html lang="en">
|
3 | <head>
|
4 | <meta charset="UTF-8" />
|
5 | <meta http-equiv="X-UA-Compatible" content="IE=edge" />
|
6 | <meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
7 | <title>策略模式</title>
|
8 | <style>
|
9 | .notify {
|
10 | width: 200px;
|
11 | height: 400px;
|
12 | border: 1px solid black;
|
13 | margin-top: 20px;
|
14 | }
|
15 | </style>
|
16 | </head>
|
17 | <body>
|
18 | <div>
|
19 | <button id="subscribe">订阅</button><button id="unsubscribe">取消订阅</button><br><br>
|
20 | <input type="text" placeholder="请输入值" id="input" /><br />
|
21 | <textarea class="notify" id="notify"></textarea>
|
22 | </div>
|
23 | <script>
|
24 | class Event {
|
25 | constructor() {
|
26 | this.subscribers = {};
|
27 | }
|
28 |
|
29 | subscribe(key, fn) {
|
30 | if (!this.subscribers[key]) {
|
31 | this.subscribers[key] = [];
|
32 | }
|
33 | this.subscribers[key].push(fn);
|
34 | }
|
35 |
|
36 | unsubscribe(key,fn) {
|
37 | let subscribers = this.subscribers[key];
|
38 | let list = [];
|
39 |
|
40 | if (!subscribers || subscribers.length === 0) return;
|
41 |
|
42 | if(!fn){
|
43 | this.subscribers[key] = [];
|
44 | return;
|
45 | }
|
46 |
|
47 | subscribers.forEach((item,index) => {
|
48 | if(item !== fn){
|
49 | list.push(fn)
|
50 | }
|
51 | })
|
52 | this.subscribers[key] = list;
|
53 | console.log(this.subscribers);
|
54 | }
|
55 |
|
56 | publish() {
|
57 | let key = Array.prototype.shift.call(arguments);
|
58 | let subscribers = this.subscribers[key];
|
59 | if (!subscribers || subscribers.length == 0) return;
|
60 | subscribers.forEach((item,index)=>{
|
61 | item(...arguments)
|
62 | })
|
63 | }
|
64 | }
|
65 |
|
66 | var publisher = new Event();
|
67 |
|
68 |
|
69 | document.getElementById("subscribe").addEventListener("click", function () {
|
70 | publisher.subscribe("notify", updateModel);
|
71 | });
|
72 |
|
73 |
|
74 | document.getElementById('unsubscribe').addEventListener('click',function(){
|
75 | publisher.unsubscribe('notify')
|
76 | })
|
77 |
|
78 |
|
79 | document.getElementById("input").addEventListener("input", function (e) {
|
80 | publisher.publish("notify", e.target.value);
|
81 | });
|
82 |
|
83 |
|
84 | function updateModel(value){
|
85 | document.getElementById('notify').value = value
|
86 | }
|
87 |
|
88 | </script>
|
89 | </body>
|
90 | </html>
|