extras.FileInputDecorator
by Ryan Duffy
JavaScript
enyo.kind({
name: "extras.FileInputDecorator",
kind: "onyx.InputDecorator",
//* @public
readOnSelect: true,
events: {
onDataRead: "",
onDataFail: ""
},
//* @private
canRead: window.File && window.FileReader,
components: [
{name:"file", kind:"enyo.Input", type:"file", showing:false, onchange:"inputChanged"}
],
inputChanged: function(inSender, inEvent) {
if(this.readOnSelect && this.canRead) {
this.read();
}
},
read: function(callback) {
if(this.canRead) {
var file = this.$.file.hasNode().files[0];
if(file) {
this.set("file", file);
var fr = new FileReader();
fr.onloadend = enyo.bind(this, function(e) {
if(fr.readyState !== 2) {
this.dataReady(callback, {error:"Read failed"});
} else {
this.dataReady(callback, {data:e.target.result.replace(/data:.*,/,"")});
}
});
fr.readAsDataURL(file);
} else {
this.dataReady(callback, {error:"No file selected"});
}
} else {
callback(this, {error:"Unsupported"});
}
},
dataReady: function(callback, result) {
this.set("data", result.data || "");
callback && callback(this, result);
this[this.data? "doDataRead" : "doDataFail"](this.data);
},
clear: function() {
this.set({
data: "",
file: null
});
}
});
enyo.kind({
name: "ex.App",
observers: {
dataChanged: ["data"]
},
bindings: [
{from:".$.file.data", to:".data"}
],
components: [
{name:"file", kind:"extras.FileInputDecorator", components:[
{name:"onyx.Button", content:"Select a File"}
]},
...