forked from MithrilJS/mithril.js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dragdrop.html
94 lines (81 loc) · 2.01 KB
/
dragdrop.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
<style type="text/css">
.uploader {background:#eee;height:200px;width:300px;}
</style>
<body><div id="test" style="background:#eee;height:100%;width:100%;"></div></body>
<script src="mithril.js"></script>
<script>
//drag and drop micro-library
function dragdrop(element, options) {
options = options || {}
element.addEventListener("dragover", activate)
element.addEventListener("dragleave", deactivate)
element.addEventListener("dragend", deactivate)
//element.addEventListener("drop", deactivate)
element.addEventListener("drop", update)
window.addEventListener("blur", deactivate)
function activate(e) {
e.preventDefault()
}
function deactivate() {}
function update(e) {
e.preventDefault()
if (typeof options.onchange == "function") {
options.onchange((e.dataTransfer || e.target).files)
}
}
}
//model entity
var Uploader = {}
Uploader.upload = function(files) {
var formData = new FormData
for (var i = 0; i < files.length; i++) {
formData.append("file" + i, files[i])
}
return m.request({
method: "POST",
url: "http://localhost/api/files",
data: formData,
//simply pass the FormData object intact to the underlying XMLHttpRequest, instead of JSON.stringify'ing it
serialize: function(value) {return value}
})
}
//an uploader module
var uploader = {}
uploader.controller = function(options) {
options = options || {}
return {
onchange: options.onchange
}
}
uploader.view = function(ctrl) {
return m(".uploader", {
config: function(element, isInitialized) {
if (!isInitialized) {
dragdrop(element, {onchange: ctrl.onchange})
}
}
})
}
//demo module
var demo = {}
demo.controller = function() {
return {
title: m.prop("Upload something"),
uploader: submodule(uploader, {
onchange: Uploader.upload
})
}
}
demo.view = function(ctrl) {
return [
m("h1", ctrl.title()),
ctrl.uploader(),
m("p", "more stuff")
]
}
m.module(document.body, demo)
//submodule helper
function submodule(module, args) {
return module.view.bind(this, new module.controller(args))
}
</script>