LiveView - phx-hook - Support for JS classes

phx-hook accepts as argument an object where its methods are the lifecycle of the callbacks (mounted, updated, etc.).

This is awesome, but it would be nice also to accept a constructor function (that would be invoked upon component instantiation), so we could make use Javascript classes. It could easily be integrated with a simple condition: javascript - How to check if a variable is an ES6 class declaration? - Stack Overflow .

let instance;
if (typeof phxHookArgument === 'function'){
  // It's a function, so it definitely can't be an instance.
  instance = new phxHookArgument();
} else {
  // It could be anything other than a constructor. Let's assume it's our regular object with callbacks.
  instance = {...phxHookArgument};
}

Using classes would allow composition patterns and better coding re-using.

Now we can use object composition, but it’s a bit limiting (no super() support, for example).

2 Likes

I agree.

I would add that the current behavior of accepting an object, that mysteriously gets copied (but without the prototype chain) is not as intuitive as providing a class that would be instantiated for each hook instances.

Is there a compelling reason behind the current choice?

I found a lib that tries to do this, but it’s quite limited and will fail miserably on classes extending other classes.

I’d gladly provide a PR if need be.

1 Like

I don’t know. It’s probably just the way it is because it’s easier to tell people to pass an object than first explaining JavaScript classes to them.

If you want to explore this, I’d be happy to review a PR!

2 Likes

That’s awesome, thanks.

I don’t know when I’ll be able to look at this, as I’m currently following a long a painful treatment that severely limits my ability to code, but I will propose something whenever I get better.