[英]Using FileReader inside object
我有一个对象,该对象具有用于解析wav文件的loadFile()
方法。 我一直在使用对象外部的FileReader
,并从读取的文件中将ArrayBuffer
加载到loadFile()
,然后从那里接管。 我想要潜在的许多对象,所以我想在loadFile()
方法中包装一个FileReader
,这样我就不必为每个对象处理所有外部的阅读器代码。 问题是,我不确定这将如何工作。 这是直观的代码:
function MyObject() {
this.property;
this.anotherProp;
this.data = new Array(); // array to be filled with PCM data for processing
}
// pass a File object
MyObject.prototype.loadFile = function(file) {
var reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = function(event) {
var buffer = event.target.result;
// do lots of stuff with buffer and eventually fill up this.data[]
}
}
MyObject.prototype.doProcessing = function() {
// process this.data[]
}
var file; // a File object I grabbed from somewhere
var myObj = new MyObject();
myObj.loadFile(file);
myObj.doProcessing();
这里的loadFile()
会发生什么? 在myObj.data[]
有任何数据之前, loadFile
返回吗? 还是会在返回前等待reader.onload
触发? 如果这是错误的方法,我应该怎么做? Aslo,如果我希望loadFile()
在reader.onload
内部失败时返回false
怎么办?
可能的解决方案: http : //jsfiddle.net/N6vnU/2/
当前解决方案:我最终将文件解析功能从对象中移到了Web worker中,并发现了FileReaderSync
。 现在,我将文件发送给网络工作者,并在返回结果后创建一个带有结果的对象。
Javascript中的事件是异步的,因此您必须假定loadFile
将在onload
运行之前返回(总是假定是最坏的情况,因为您无法预测异步调用何时完成)。
通常的选择是将一个回调参数添加到loadFile
,一旦完成onload
,您将调用该参数,或者如果愿意的话,还可以选择集成延期/未来功能。
另外一个暗示:你需要调用readAsArrayBuffer
分配后 onload
处理程序,因为又因为它是异步总有那么你会错过这个事件,如果你第一次指示浏览器读取该文件,然后一个事件附加给它的机会。
是的,将在实际加载文件之前返回加载文件。 一个好的方法可能涉及使用诺言。
例如,您可以使用Q库。 这是指向API的链接: https : //github.com/kriskowal/q/wiki/API-Reference
如果您已经使用jQuery,即使我建议您使用Q库提供的Promise,$ .Deferred对象也足够了。
MyObject构造函数可以定义一个reader.onload
函数解析的延迟的(最好是私有的)。
对MyObject实例的实际用途了解甚少,请考虑阅读以下内容作为伪代码。
function MyObject() {
this.def = $.Deferred(); //the deferred to be resolved when the content has been loaded
this.property;
this.anotherProp;
this.data = new Array(); // array to be filled with PCM data for processing
}
// pass a File object
MyObject.prototype.loadFile = function(file) {
var obj = this,
reader = new FileReader();
this.def = $.Deferred();
reader.readAsArrayBuffer(file);
reader.onload = function(event) {
var buffer = event.target.result;
obj.def.resolve();
// do lots of stuff with buffer and eventually fill up this.data[]
}
}
MyObject.prototype.doProcessing = function() {
this.def.done(function(){
// process this.data[]
console.log('resolved');
});
}
var file; // a File object I grabbed from somewhere
var x = new MyObject();
x.loadFile(file);
x.doProcessing(); //this would print 'resolved' when the file is loaded
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.