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