Emma
Emma

Reputation: 314

Binding html events to es6 modules

Before the new es6 module syntax, whenever i wanted to link some html action to javascript it would look like this:

myPage.html:

<html>
    <head>
        <script src="myScript.js" async></script>
    </head>
    <body>
        <p id="button" onclick="doStuff();">Do Stuff</p>
    </body>
</html>

myScript.js:

function doStuff() {
    ...
}

This all all straightforward and simple. But now to the es6 modules. They don't expose functions to the global scope so we eiter need to

  1. Expose our functions to the global scope (window.doStuff = () => { ... })
  2. Link our html and js from within the js module (document.getElementbyId('button').onclick=doStuff)

Is any of these ways preferred over the other? I understand this question might well be closed as opinion based but i'll be cheeky and ask only if Ecma mentions it in their specs/docs somewhere? Surely they must have thought of this

Upvotes: 3

Views: 2320

Answers (1)

Ori Drori
Ori Drori

Reputation: 191936

Although the attaching events directly in the DOM is still supported, this is an old paradigm that couples the HTML and JS tightly. In addition, you can only add one handler for each event (click for example).

It was suppressed by referencing the elements and in JS, and then attaching the event handlers using addEventListener/removeEventListener or jQuery (or another library) equivalents.

const button = document.querySelect('#button');
const event handler = (ev) => { /..../ };

button.addEventListener('click', handler);
button.removeEventListener('click', handler);

Note: the onclick style of event handling came back in modern frameworks, such as angular, react, and vue. They have directives/props that mimic the old declarative way of attaching events - ng-click, onClick, v-on:click, but under the hood they bind the events using addEventListener (the imperative style).

Upvotes: 4

Related Questions