2

I was working on a very simple electron app, following a guide on Youtube and the teacher has me put an event listener on a button, like so:

button.addEventListener('click', ()=> {
    main.openWindow();
});

Standard stuff. main is from using Electron's remote module to allow me to grab the exports object off the main js file that runs the electron. openWindow() is the exported function and it opens an Electron window. And it works.

I thought I'd make it tighter by doing this:

button.addEventListener('click', main.openWindow);

Except I get an error when I click on the button:

Uncaught Error: No such module: atom_common_app

I'm not sure I understand the difference between the first snippet and the second. The first uses an anonymous function that calls my exported function, the other gives the add event listener a reference to that function to use when the button is clicked on. I don't understand why one works and the other does not. What is the difference between the first snippet and the second?

Thanks

Jonathan Kuhl
  • 699
  • 9
  • 23
  • 1
    Simillar: https://stackoverflow.com/questions/21298918/is-it-possible-to-call-a-class-method-with-addeventlistener – ibrahim mahrir Apr 25 '18 at 23:11
  • 1
    Also: https://stackoverflow.com/questions/30446622/es6-class-access-to-this-with-addeventlistener-applied-on-method – ibrahim mahrir Apr 25 '18 at 23:16
  • 1
    **Bottom line:** In the first example, the **`this`** inside `openWindow` will be your `main` object. In the second it will be the DOM element that fired the event. Apparently `openWindow` uses `this` internally and it's expecting it to be `main`. In the first example, the function that get bound to the DOM element as its `this` value is the arrow function (that doesn't even have a `this` value anyway). In the second, it's `openWindow` – ibrahim mahrir Apr 25 '18 at 23:25
  • This might work: `button.addEventListener('click', main.openWindow.bind(main));` –  Apr 25 '18 at 23:31

0 Answers0