Skip to content

Commit 51be59f

Browse files
committed
added mediator pattern
1 parent bb9397d commit 51be59f

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

design-patterns/mediator.html

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<title>JavaScript Patterns</title>
5+
<meta charset="utf-8">
6+
</head>
7+
<body>
8+
<script>
9+
function Player(name) {
10+
this.points = 0;
11+
this.name = name;
12+
}
13+
Player.prototype.play = function () {
14+
this.points += 1;
15+
mediator.played();
16+
};
17+
var scoreboard = {
18+
19+
// HTML element to be updated
20+
element: document.getElementById('results'),
21+
22+
// update the score display
23+
update: function (score) {
24+
var i, msg = '';
25+
for (i in score) {
26+
if (score.hasOwnProperty(i)) {
27+
msg += '<p><strong>' + i + '<\/strong>: ';
28+
msg += score[i];
29+
msg += '<\/p>';
30+
}
31+
}
32+
this.element.innerHTML = msg;
33+
}
34+
};
35+
36+
var mediator = {
37+
38+
// all the player
39+
players: {},
40+
41+
// initialization
42+
setup: function () {
43+
var players = this.players;
44+
players.home = new Player('Home');
45+
players.guest = new Player('Guest');
46+
},
47+
48+
// someone plays, update the score
49+
played: function () {
50+
var players = this.players,
51+
score = {
52+
Home: players.home.points,
53+
Guest: players.guest.points
54+
};
55+
56+
scoreboard.update(score);
57+
},
58+
59+
// handle user interactions
60+
keypress: function (e) {
61+
e = e || window.event; // IE
62+
if (e.which === 49) { // key "1"
63+
mediator.players.home.play();
64+
return;
65+
}
66+
if (e.which === 48) { // key "0"
67+
mediator.players.guest.play();
68+
return;
69+
}
70+
}
71+
};
72+
73+
// go!
74+
mediator.setup();
75+
window.onkeypress = mediator.keypress;
76+
77+
// game over in 30 seconds
78+
setTimeout(function () {
79+
window.onkeypress = null;
80+
console.log('Game over!');
81+
}, 30000);
82+
83+
</script>
84+
</body>
85+
</html>

0 commit comments

Comments
 (0)