Search code examples
javascriptcxjs

How to add active event listener for onWheel event in CxJS?


I have a div, on which I want to add an onWheel event listener and prevent the default behavior.

onWheelAction(e, {store}) {
   e.prevetDefault();
   ...
}
<div onWheel="onWheelAction">
   ...
</div>

This throws an error that preventDefault cannot be done in the passive event listener. How can I convert it to an active listener?


Solution

  • onWheel is a passive event listener from React (here) and Cx does not override it.

    To make this work, instead of onWheel, you can use onRef attribute, which accepts a callback, with the first parameter being the element. Then, you can add an active listener on that element with the addEventListenerWithOptions method which is available in Cx, and prevent default behavior.

    import { addEventListenerWithOptions } from 'cx/util';
    
    let unsubscribeScroll: () => void;
    
    addElementListener(el: Element) {
        if (unsubscribeScroll) unsubscribeScroll();
        if (!el) return;
        unsubscribeScroll = addEventListenerWithOptions(
        el,
        'wheel',
        (e: any) => {
            e.preventDefault();
                 ...
           },
         { passive: false }
        );
    }
    <div onRef='addElementListener'>
      ...
    </div>