neil
neil

Reputation: 92

Events in function arguments

I'm new to javascript and am trying to teach myself some of it by looking at code for online projects that I find interesting. I was going through a 3D viewer's code (source). It allows you to drag and drop 3D data files that you want to view. In the drop bit of the code (shown below), there are a few things that seem unclear:

  1. reader.onload = function (event) ... Not sure what the 'event' here is.
  2. reader.readAsText(file);... Not sure why this is done since reader.readAsBinaryString(file); has been invoked earlier.

Thanks a lot in advance, people :).

    function onFileDrop(evt) {

        evt.stopPropagation();
        evt.preventDefault();

        var file = evt.dataTransfer.files[0]; 

        var splits = file.name.split('.');

        if (splits[splits.length - 1] == 'json') {

            var reader = new FileReader();

            //reader.onerror = errorHandler;
            //reader.onprogress = updateProgress;
            //reader.onabort = 
            //reader.onloadstart = 
            //reader.onload = 

            reader.readAsBinaryString(file);

            reader.onload = function (event) {

                var meshEntityList = JSON.parse(event.target.result);

                createScene(meshEntityList);
            };

            reader.onerror = function (event) {
                alert('Cannot read file!');
            };

            reader.readAsText(file);
        }
    }

Upvotes: 4

Views: 58

Answers (1)

Lance
Lance

Reputation: 3932

  1. reader is instantiated and given a binary file to read. If it succeeds, it passes its exit code as 'event' and processes the file. If it fails, it passes the error code as 'event' and displays the error. The word 'event' here is arbitrary.

  2. It just looks weird because of the asynchronous nature of javascript. The onload and onerror are event handlers. If the reader.readAsText(file); statement immediately followed the reader.readAsBinaryString(file); statement, and they both came after the event handlers it might make more sense but it would behave exactly the same. If both those statements fail the error will fire but if either succeeds then the onload will fire.

Upvotes: 1

Related Questions