Knockoutjs.com - Hello World Example
http://knockoutjs.com/examples/helloWorld.html
by suhail
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<input type="file" data-bind="fileUpload: uploadFile">
<br/>
<br/>Selected file name: <span data-bind="text: uploadName"></span>
<br/>
<button data-bind="click: clear">Clear input</button>
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
function Example() {
var self = this;
self.uploadFile = ko.observable(null);
self.uploadName = ko.computed(function() {
return !!self.uploadFile() ? self.uploadFile().name : '-';
});
self.clear = function() {
console.log(self.uploadFile());
self.uploadFile(null);
};
};
ko.bindingHandlers.fileUpload = {
init: function(element, valueAccessor) {
$(element).change(function() {
valueAccessor()(element.files[0]);
});
},
update: function(element, valueAccessor) {
if (ko.unwrap(valueAccessor()) === null) {
$(element).wrap('<form>').closest('form').get(0).reset();
$(element).unwrap();
}
}
};
ko.applyBindings(new Example());