Last active
May 25, 2016 15:45
-
-
Save davidchase/a76dba25c8c76231971bd89062070f15 to your computer and use it in GitHub Desktop.
FileReader API with most
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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