forked from MithrilJS/mithril.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mvc.html
96 lines (87 loc) · 2.06 KB
/
mvc.html
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
<body></body>
<script src="mithril.js"></script>
<script>
var Reloadable = new function() {
var controllers = []
var reloadable = function(controller) {
return function() {
var ctrl = new controller
ctrl.onunload = function() {
controllers.splice(controllers.indexOf(ctrl), 1)
}
controllers.push({instance: ctrl, controller: controller})
return ctrl
}
}
reloadable.update = function() {
controllers.map(function(c) {
ctrl = new c.controller
for (var i in ctrl) c.instance[i] = ctrl[i]
})
}
return reloadable
}
var saved = []
var Contact = function(data) {
data = data || {}
this.id = m.prop(data.id)
this.name = m.prop(data.name || "")
this.email = m.prop(data.email || "")
}
Contact.list = function(data) {
return m.request({method: "GET", url: "test.json", data: data, type: Contact})
.then(function(contacts) {return contacts.concat(saved)})
}
Contact.create = function(data) {
data.id(saved.push(data) + 2)
return Contact.list()
}
var ContactsWidget = {
controller: function() {
},
view: function(ctrl) {
return [
m.module(ContactForm),
m.module(ContactList)
]
}
}
var ContactForm = {
controller: function(args) {
var contact = m.prop(new Contact())
return {
contact: contact,
createContact: function() {
Contact.create(contact()).then(Reloadable.update)
},
}
},
view: function(ctrl) {
var contact = ctrl.contact()
return m("form", [
m("label", "Name"),
m("input", {oninput: m.withAttr("value", contact.name), value: contact.name()}),
m("label", "Email"),
m("input", {oninput: m.withAttr("value", contact.email), value: contact.email()}),
m("button[type=button]", {onclick: ctrl.createContact}, "Create")
])
}
}
var ContactList = {
controller: Reloadable(function() {
return {contacts: Contact.list()}
}),
view: function(ctrl) {
return m("table", [
ctrl.contacts().map(function(contact) {
return m("tr", [
m("td", contact.id()),
m("td", contact.name()),
m("td", contact.email())
])
})
])
}
}
m.module(document.body, ContactsWidget)
</script>