PDA

View Full Version : File API: reader vs. event.target



Rain Lover
05-20-2014, 06:43 PM
I have studied many articles and posts to learn about File API and still don't understand why almost all of them use event.target instead of reader. Here are three examples:


File API (http://www.w3.org/TR/FileAPI/#introduction)
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications#Example.3A_Showing_thumbnails_of_user-selected_images
Working with files in JavaScript, Part 2: FileReader | NCZOnline (http://www.nczonline.net/blog/2012/05/15/working-with-files-in-javascript-part-2/)


The last reference even recommends using event.target:


The FileReader instance is available inside of the event handler via event.target and it’s recommended to use that instead of referencing the reader variable directly.

But why is it recommended and widely used? What's wrong with using reader or simpler this instead: DEMO (http://jsfiddle.net/Mori/tJBHZ/).

I know this and event.target can be different, but in this case they both refer to the FileReader object.


reader: an instance of FileReader;
onload: a FileReader event (https://developer.mozilla.org/en-US/docs/Web/API/FileReader#Event_handlers);
result: a FileReader property (https://developer.mozilla.org/en-US/docs/Web/API/FileReader#Properties);


While you can use reader.onload, then why not reader.result?

jscheuer1
05-21-2014, 01:45 AM
I'm unfamiliar with this particular script. However there generally are many ways to refer to any given element. And it frequently happens that many elements may be initialized by a single function that reacts to an event on any one of them. At that point the event target is often the more specific way of referring to the element that has had the event occur upon it. However, this way of looking at things is no substitute for understanding which element has been initialized and which element has received the event (sometimes two different elements) and how to obtain - at event time or before, a reference to the desired element or object required to access the properties sought in successfully executing the code. If a particular code's author recommends a particular approach, it's usually best for that code. But other methods may also work, or even be better. We usually can rely upon author recommendations though because they reflect a greater volume of experience with the particular code.