forked from jessmand/MITx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmvc.js
98 lines (67 loc) · 2.29 KB
/
mvc.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
87
88
89
90
91
92
93
94
95
96
97
98
var counter = (function () {
function EventHandler() {
var handlers = {}
function on(eventString, callback) {
var cblist = handlers[eventString];
if (cblist === undefined) {
cblist = [];
handlers[eventString] = cblist;
}
cblist.push(callback);
}
function trigger(eventString, data) {
var cblist = handlers[eventString];
if (cblist !== undefined) {
for (var i = 0; i<cblist.length; i++) {
cblist[i](data);
}
}
}
return {on: on, trigger: trigger};
}
function Model() {
var count = 0;
var eventHandlers = EventHandler()
function increment() {
count++;
eventHandlers.trigger('update', count);
}
function reset() {
count = 0;
}
function getValue() {
return count;
}
return {increment: increment, reset: reset, getValue: getValue, on: eventHandlers.on};
}
function Controller(model) {
function increment() {
model.increment();
}
return {increment: increment};
}
function View(div, model, controller) {
var display = $("<div class='view'>The current value of the counter is <span>0<span>.</div>");
var counterValue = display.find("span");
div.append(display);
function update() {
counterValue.text(model.getValue());
}
model.on('update', update);
}
function setup(div) {
var model = Model();
var controller = Controller(model);
var view = View(div, model, controller);
var view2 = View(div, model, controller);
var button = $("<button>Increment</button>");
button.on("click", controller.increment);
div.append(button);
}
return {setup: setup};
}());
$(document).ready(function () {
$('.counter').each(function () {
counter.setup($(this));
});
});