-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmediator.js
86 lines (73 loc) · 1.89 KB
/
mediator.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// http://thejacklawson.com/Mediator.js/
// 多个情况
var mediator = (function () {
var channels = {};
var subscribe = function (channel, fn) {
if (!channels[channel])
channels[channel] = [];
channels[channel].push({ context: this, callback: fn });
return this;
}
var publish = function (channel) {
if (!channels[channel]) return false;
var args = Array.prototype.slice.call(arguments, 1);
for (var i = 0, l = channels[channel].length; i < l; i++) {
var subscription = channels[channel][i];
subscription.callback.apply(subscription.context, args);
}
return this;
};
return {
publish: publish,
subscribe: subscribe,
installTo: function (obj) {
obj.subscribe = subscribe;
obj.publish = publish;
}
};
}());
(function (m) {
var person = {
name: "Luke",
age: 20
};
m.subscribe('nameChange', function (arg) {
console.log(person.name); // Luke
person.name = arg;
console.log(person.name); // David
});
m.subscribe('ageChange', function (arg) {
console.log(person.age)
person.age = arg
console.log(person.age)
})
m.publish('nameChange', 'David');
m.publish('ageChange', '22')
})(mediator);
// 不完善版本
const mediator = (function () {
let channels = {}
let subscribe = function (channel, fn) {
channels[channel] = { context: this, callback: fn }
}
let publish = function (channel) {
var args = Array.prototype.slice.call(arguments, 1);
channels[channel].callback.apply(channels[channel].context, args)
}
return {
subscribe: subscribe,
publish: publish
}
}())
(function (m) {
var person = {
name: "Luke",
age: 20
};
m.subscribe('nameChange', function (arg) {
console.log(person.name); // Luke
person.name = arg;
console.log(person.name); // David
});
m.publish('nameChange', 'David');
})(mediator);