简体   繁体   English

JavaScript代码重构

[英]Javascript code refactoring

I have the following code which is working 我有下面的代码正在工作

var exif = function(exifObject) {
    alert(exifObject.Orientation);
}

$(this).fileExif(exif);

Problem is, I need the alerted value after $(this).fileExif(exif) line. 问题是,我需要$(this).fileExif(exif)行之后的警报值。

So I tried doing the following: 因此,我尝试执行以下操作:

function getOrientation(exifObject){
    return(exifObject.Orientation);
}
getOrientation($(this).fileExif());

It does not work. 这是行不通的。 How could I achieve to have the alerted value after $(this).fileExif(exif) line? 我怎样才能在$(this).fileExif(exif)行之后获得警报值?

Additional info 附加信息

console.log(exifObject) returns an Object with an array of attributes, fe Orientation . console.log(exifObject)返回一个带有属性数组的对象,例如console.log(exifObject) Orientation

$(this) is wrapped in this code: $(this)包装在以下代码中:

$('body').on('change', '#imgFile', function(event) {

so it's an input type file. 所以它是一个输入类型文件。

You are passing exif , which is a function, to the fileExif function. 您正在将exif (这是一个函数)传递给fileExif函数。 This is an example of the fact that functions are first-class objects in JavaScript, and in this case exif is a "callback" function. 这是一个事实,即函数是JavaScript中的一流对象,并且在这种情况下, exif是“回调”函数。 That is, when the fileExif function is finished, it passes it's result to the exif function, which is then called. 也就是说,当fileExif函数完成时,它将结果传递给exif函数,然后调用该函数。

In terms of execution, the alert will be called after the fileExif function. 在执行方面, alert将在fileExif函数之后调用。 However, if you desperately want the code to be written after the function, you could declare the function as you pass it: 但是,如果您非常希望在函数之后编写代码,则可以在传递函数时声明该函数:

$(this).fileExif(function(exifObject) {
    alert(exifObject.Orientation);
});

However, this is probably not as clear as the original. 但是,这可能不像原始的那样清晰。

I find only one fileExif plugin for jQuery. 我只找到一个用于jQuery的fileExif插件。 Here it sources . 这里是来源 This plugin use native FileReader . 该插件使用本机FileReader FileReader load file asynchronously. FileReader异步加载文件。 You have 2 way. 你有两种方法。 First - modify plugin code and make it sync (bad idea). 首先-修改插件代码并使其同步(不好的主意)。 Write your code with asycn style (best practice). 用asycn风格编写代码(最佳实践)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM