4

Using Public Class Fields To Bind Event Handlers In JavaScript

 1 year ago
source link: https://www.bennadel.com/blog/4443-using-public-class-fields-to-bind-event-handlers-in-javascript.htm
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Using Public Class Fields To Bind Event Handlers In JavaScript

By Ben Nadel on April 8, 2023

When I started using Angular with TypeScript, I was delighted to see that TypeScript offered a way to bind Functions to a Class instance as part of the Class definition. It worked by moving the "Function definition" into the constructor() method during compilation. This feature of TypeScript is amazing; and, I'm thrilled to see that this feature has also been adopted by the JavaScript specification. This allows us to easily bind event handlers without having to use .bind() or pass-in inline Fat-Arrow functions within our JavaScript classes.

Run this demo in my JavaScript Demos project on GitHub.

View this code in my JavaScript Demos project on GitHub.

When you pass a Function reference out-of-context as part of a callback mechanism, you often lose the this binding associated with the Function. This is why the Fat-Arrow syntax was such a huge step forward for the JavaScript language: it allowed us to pass-around Functions that retained their original this binding regardless of how they were eventually invoked.

The Fat-Arrow function, combined with Public Class Fields, bring that same level of elegance into our class-based event-handlers. When defining a class method that will act as a callback, instead of defining it as a Function Declaration, we can define it as a Function Expression that is assigned to a class property.

So, instead of doing this:

... where callback() is being defined on the Class prototype chain, we can do this:

Here, the callback property of the class is being initialized to point to a per-instance Fat-arrow function. This way, the callback Function is always bound to a this reference which refers to our instantiated MyClass instance.

To see this in action, let's create a Class that manages click events for a simple counter. The class has an internal method, handleClick, which is being defined as a public class property using a Fat-Arrow function:

As you can see, in my CounterController class definition, the handleClick "method" is actually just a "public class field" that's being initialized with a Fat-Arrow function. And, by defining the class in such a way, it allows us to attach our a click handler by passing around a "naked" Function reference:

.addEventListener( "click", this.handleClick );

Notice that we're not calling anything like .bind(this) on the Function reference. Instead, we're allowing our Fat-Arrow function to manage the this binding within our callback.

Now, if we run this code in the browser, we can see that all the bindings between the callbacks and the class properties work perfectly:

Clicking the button increments the counter and updates the view rendering.

As you can see, when the button is clicked, our handleClick callback clearly has no problem referencing the .value and .valueTarget properties bound to the CounterController instance. This is because the Fat-Arrow syntax retains its binding even when the Function is passed out-of-scope.

Gone are the days of calling .bind() on Functions in our Class constructors! Now, by combining Fat-Arrow functions with public class fields, we can easily create bound-methods as part of our class specification. Handling events (and event callbacks) has never been so sweet!

Want to use code from this post? Check out the license.

Enjoyed This Post? ❤️ Share the Love With Your Friends! ❤️

Tweet This Titillating read by @BenNadel - Using Public Class Fields To Bind Event Handlers In JavaScript https://www.bennadel.com/go/4443

Reader Comments

What has two thumbs and hopes you leave a comment? This Guy! (Ben Nadel).

Post A Comment — ❤️ I'd Love To Hear From You! ❤️

Name:

Email:

Website:

Comment:
NEW: Some basic markdown formatting is now supported: bold, italic, blockquotes, lists, fenced code-blocks. Read more about markdown syntax »
Comment Etiquette: Please do not post spam. Please keep the comments on-topic. Please do not post unrelated questions or large chunks of code. And, above all, please be nice to each other - we're trying to have a good conversation here.

Subscribe to comments.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK