Losing the event listeners when changing from "preview" to "edit" mode

43 Views Asked by At

I have some elements in the layout which are controlled with the event listeners. An issue appears when I go from the 'view mode' into an 'edit mode' and the event listeners no longer work. My guess is that changing the mode from view to edit creates a second version of the DOM and the event listeners attached during the initial page render no longer function. Have you had such an issue before? What would be the best way to tackle it?

1

There are 1 best solutions below

0
alexbea On

There is relatively recent documentation related to this specific use case: https://v3.docs.apostrophecms.org/guide/front-end-tips.html#register-js-to-keep-up-with-in-context-editing-events

The short version is that there is a helper method on the front end that helps you run client-side code every time the DOM refreshes, apos.util.onReady:

// modules/assets/ui/src/index.js
export default () = {
  if (document.querySelector('[data-party-toggle]')) {
    // 
    apos.util.onReady(() => {
      const partyToggle = document.querySelector('[data-party-toggle]');

      partyToggle.addEventListener('click', engagePartyMode);

      function engagePartyMode () {
        // Party.
      }
    });
  }
}

If the element you are adding the listener to is a widget and the code is limited to the widget type, then use a widget player instead.