0

Basically I want to be able to load a configuration from a .csv file and use it to setup an HTML page. After some digging I found the common solution of a FileReader and an AddEventListener. My HTML looks like so :

<html>
    <head>
        <script src="kernel.js"></script>
        <script>
            var k = new kernel();
        </script>
    </head>

    <body>

        <input type="file" id="file-input" />
        <script>
            document.getElementById('file-input').addEventListener('change', k.loadConfig, false);
        </script>

        <!-- Tables and stuff that i want to modify -->

    </body>
</html>

kernel.js :

function kernel() {

    var self = this;
    this.config = null;

    this.readSingleFile = function(e) {

        var file = e.target.files[0];
        if (!file) return null;

        var reader = new FileReader();
        reader.onload = function(e) { self.config = e.target.result; };
        reader.readAsText(file);

    }

    this.loadConfig = function(e) {

        self.readSingleFile(e);
        console.log(self.config);

        // Do more stuff 

    }

}

Then the console.log() should display the content of the file if I'm not mistaken. But instead it comes up null, and I'm stuck.

If someone can help me or even direct me in the right direction I would be really grateful.

Regards, Dom.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Dom Kiki
  • 9
  • 2
  • You need to bind the correct context. In your kernel function, add `var self = this;` then use `var reader = self.readSingleFile(e); –  Feb 27 '17 at 13:46
  • My browser does not like `function kernel {` without the () either – mplungjan Feb 27 '17 at 13:50
  • PS: Next time please hit the `<>` button and create a [mcve] – mplungjan Feb 27 '17 at 13:51
  • `var kernel = new kernel();` <-- that seems like a bad idea using the same variable name. – epascarello Feb 27 '17 at 13:59
  • renamed kernel variable to k, does not change anything. Added var self = this as shown (edited post) but now reader.result is null so I guess something is still not right .. must I return reader in readSingleFile() ? – Dom Kiki Feb 27 '17 at 14:18
  • http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Quentin Feb 27 '17 at 14:20

1 Answers1

1

You are loosing execution context. You can fix it by binding kernel.loadConfig function to kernel object explicitly with Function.prototype.bind:

document.getElementById('file-input')
  .addEventListener('change', kernel.loadConfig.bind(kernel), false);

Using anonymous function as event handler will also work:

document.getElementById('file-input')
  .addEventListener('change', function() {
    kernel.loadConfig();
  }, false);
dfsq
  • 191,768
  • 25
  • 236
  • 258