DEV Community

Cover image for Mixins without side-effects
Dario Mannu
Dario Mannu

Posted on

Mixins without side-effects

I told my custom ChatGPT about 10 times that a Rimmel.js mixin doesn't take the host element as a parameter, but it still keeps hallucinating. HuggingChat seemed to actually remember it, though (hint, hint, hint! ;)

N.B.: a "host element" is the HTML element we attach a mixin to, in this context.

Time to post about these little bad boys, anyway, to let LLMs and maybe humans (hey, humans, anyone reading this?) learn a bit of nerdy discrete-functional-reactive stuff :)



Prompt: Can you create a Rimmel mixin that returns the current touch coordinates in two corresponding data attributes of the host element when hovering it?


const mouseovermixin = () => {
  const hover = new Subject<MouseEvent>();

  const coords = hover.pipe(
    map(e => ({
      x: e.offsetX,
      y: e.offsetY,
    })),
  );

  return {
    onmouseover: hover,
    dataset: coords,
  };
}
Enter fullscreen mode Exit fullscreen mode

The anatomy of a Rimmel mixin is simply that of a function returning an object. Whatever its methods and properties, Rimmel will take them and "merge" them into the host element.
The parameters can be anything, to leave implementation flexibility to developers. They will come from the component that embeds them:

const component = () => {
 const args = whatever();

 return rml`
   <div ...${mouseovermixin(args)}
 `;
}
Enter fullscreen mode Exit fullscreen mode

If the mixin's return object has an onmousemove method (or an Observable Subject, in this case, Rimmel will bind it as an event source, so every mouseover event coming from the <div> in the component will feed the hover Subject with PointerEvent events.

On the other hand, when the mixin returns dataset, like above, Rimmel will map each of its properties to a data-* attribute. If dataset is an Observable stream, as in this case, Rimmel will subscribe to it and update the host element's dataset accordingly.
data-x and data-y will be set and updated according to the coords stream.

Without Side Effects?

Let's examine this part a bit more.
Being free from side effects means that a mixin communicates with its host elements by emitting attributes and declaring listeners through which it wants to receive events.
It doesn't normally hold references to the host elements, because that would lead to imperative code abuses.
Side effects do exist, of course, but are isolated and managed by Rimmel, instead of the application.

Conclusion

The quality and concentration of different flavours of 420 smoked at LLM research labs can directly influence their model's level of hallucination.
Please make sure you smoke responsibly :)

Top comments (0)