[英]Pass additional parameter to callback function
I have a pretty simple function that is reading a file with HTML 5 FileReader: 我有一个非常简单的功能,可以使用HTML 5 FileReader读取文件:
var reader = new FileReader();
var currentFileType = file.type;
reader.onloadend = readCompleted;
reader.onerror = fail;
reader.readAsArrayBuffer(file);
and the readCompleted callback function looks like this: 而readCompleted回调函数如下所示:
function readCompleted(evt) {
if (evt.target.readyState != FileReader.DONE) {
return;
}
// The binary data is the result.
var requestData = evt.target.result;
// SOME MORE CODE HERE
}
Thing is that 'evt' parameter is passed by default. 问题是默认情况下会传递“ evt”参数。 How can I pass one additional parameter to this callback function in order to have currentFileType variable available?
如何将一个附加参数传递给此回调函数,以使currentFileType变量可用? I want this function signature to look like this:
function readCompleted(evt, fileType) {//code here}
and pass somehow currentFileType to it. 我希望此函数签名看起来像这样:
function readCompleted(evt, fileType) {//code here}
并以某种方式将currentFileType传递给它。
You can use Function.bind
to bind an argument to the function before assigning it to onloadend
. 您可以使用
Function.bind
将参数绑定到函数,然后再将其分配给onloadend
。
For example: 例如:
var a = function() { console.log(arguments); }
var b = a.bind(null, 123)
b('abc') // -> [123, "abc"]
In your case, it would be: 在您的情况下,它将是:
reader.onloadend = readCompleted.bind(null, file.type);
and readCompleted
should have the following signature: 和
readCompleted
应该具有以下签名:
function readCompleted(fileType, evt) { ... }
Just assign a different function to reader.onloadend
. 只需将不同的功能分配给
reader.onloadend
。
reader.onloadend = function(evt) {
readCompleted(evt, currentFileType);
};
You can write like this, 你可以这样写
var reader = new FileReader();
var currentFileType = file.type;
reader.onloadend = function(evt){
readCompleted(evt,currentFileType);
};
reader.onerror = fail;
The readCompleted will look like this, readCompleted看起来像这样,
function readCompleted(evt,ft) { //code... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.