Knockoutjs.com - Hello World Example
http://knockoutjs.com/examples/helloWorld.html
HTML
<script src="http://knockoutjs.com/downloads/knockout-2.2.1.js"></script>
<div class='liveExample'>
<input data-bind="event: { change: function() { uploadImage($elemet.files[0]) } }" style="width: 10px;" type="file">
<a data-bind="click: triggerImageInputOne" class="image-content-editing-link">or upload from computer</a>
</div>
CSS
.liveExample {
font-family: arial;
font-size: 14px;
padding: 1em;
background-color: #EEEEDD;
border: 1px solid #CCC;
max-width: 655px;
}
.liveExample input {
font-family: Arial;
}
.liveExample b {
font-weight: bold;
}
.liveExample p {
margin-top: 0.9em;
margin-bottom: 0.9em;
}
.liveExample select[multiple] {
width: 100%;
height: 8em;
}
.liveExample h2 {
margin-top: 0.4em;
font-weight: bold;
font-size: 1.2em;
}
.image-content-editing-link {
line-height: 60px;
width: 100% !important;
font-family: "Segoe UI", Frutiger, "Frutiger Linotype", "Dejavu Sans", "Helvetica Neue", Arial, sans-serif;
cursor: pointer;
}
JavaScript
var ViewModel = function () {
var self = this;
self.triggerImageInputOne = function () {
document.querySelector('input' + self.cardId()).click();
};
self.uploadImage = function (file) {
console.log(file);
/* Is the file an image? */
if (!file || !file.type.match(/image.*/)) return;
/* It is! */
document.body.className = "uploading";
/* Lets build a FormData object*/
var fd = new FormData();
fd.append("image", file); // Append the file
fd.append("key", "262662626262");
var xhr = new XMLHttpRequest(); //
xhr.open("POST", "http://api.imgur.com/2/upload.json");
xhr.onload = function () {
document.querySelector("#link").href = JSON.parse(xhr.responseText).upload.links.imgur_page;
document.body.className = "uploaded";
}
/* And now, we send the formdata */
xhr.send(fd);
};
};
ko.applyBindings(new ViewModel());