Skip to content

Instantly share code, notes, and snippets.

@davidchase
Last active May 25, 2016 15:45
Show Gist options
  • Save davidchase/a76dba25c8c76231971bd89062070f15 to your computer and use it in GitHub Desktop.
Save davidchase/a76dba25c8c76231971bd89062070f15 to your computer and use it in GitHub Desktop.
FileReader API with most
// http://www.webpackbin.com/NyiticRzb
import {Stream} from 'most';
import {change} from '@most/dom-event';
const fromFileReader = (method, type, stream) => new Stream(new FileReaderSource(method, type, stream));
class FileReaderSource {
constructor(method, type, stream) {
this.method = method;
this.type = type;
this.source = stream.source;
}
run(sink, scheduler) {
return this.source.run(new FileReaderSink(this.method, this.type, sink), scheduler);
}
}
class FileReaderSink {
constructor(method, type, sink) {
this.method = method;
this.type = type;
this.sink = sink;
}
event(time, value) {
const files = value.target.files;
const sink = this.sink;
const method = this.method;
const type = this.type;
for (let i = 0, len = files.length; i < len; i++) {
if (!files[i].type.match(type)) continue;
const reader = new FileReader();
reader.addEventListener('load', sink.event.bind(sink, time), false);
reader[method](files[i]);
}
}
error(time, err) {
return this.sink.error(time, err);
}
end(time, value) {
return this.sink.end(time, value);
}
}
fromFileReader('readAsDataURL', 'image', change(document.body))
.observe(console.info.bind(console))
.catch(console.error.bind(console));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment