NodeJS module running before the EventListener

2

I am creating a module for node and when performing some tests with eventListener of type change in a field of type file , the module is executed before a file is inserted in the field. p>

exports.preview = (fileInput, whereToSee) => {
    if (fileInput && fileInput[0]) {
        let reader = new FileReader();
        reader.onload = (event) => {
            whereToSee.attr('src', event.target.result);
        }
        reader.readAsDataURL(fileInput[0]);
     } else {
        console.error('None!!'); // Mensagem de teste
    }

}

The Test Code:

var upload = require('../index.js');

const file = document.querySelector('input[type="file"]');

file.addEventListener('change', upload.preview(this, document.querySelector('#blah')));

As soon as I open the browser the message None!! is displayed, that is, the change event is activated even before a file is selected.

I'm using webpack to create bundle.js from the file main.js which is the file where the test codes are located:

  

webpack main.js bundle.js

    
asked by anonymous 16.03.2017 / 21:54

1 answer

2

You have to use the concept of high order function , that is to return a function for .addEventListener call, a callback in this case.

It could look like this:

exports.preview = (fileInput, whereToSee) => {
    return function(){
        if (fileInput && fileInput[0]) {
            let reader = new FileReader();
            reader.onload = (event) => {
                whereToSee.attr('src', event.target.result);
            }
            reader.readAsDataURL(fileInput[0]);
         } else {
            console.error('None!!'); // Mensagem de teste
        }
    }
}

In this way when you invoke the function as you have in your code, as an argument of addEventListener , it captures the variables in the callback scope that you return. This callback will be called when there is change .

    
16.03.2017 / 22:19