Skip to content

Instantly share code, notes, and snippets.

@snewcomer
Last active October 21, 2019 00:15
Show Gist options
  • Save snewcomer/ab6405df11088ebbd19e96da661e7154 to your computer and use it in GitHub Desktop.
Save snewcomer/ab6405df11088ebbd19e96da661e7154 to your computer and use it in GitHub Desktop.
Phoenix Live View DOM Events thoughts

DOM Event Order

  • Events execution order is not guaranteed based on the heirarchy of the DOM when using window.addEventListener. Instead window.addEventListener will run listeners in the order they are registered.
  • DOM3 specifies events flow down the DOM tree and then back up. addEventListener's are called on the way back up, but can be called as evt propogates down the tree with true for the useCapture argument.

Ideas

Taking control of event listeners for the user limits a lot of the flexibility the DOM + JS provides. See this issue for an example.

Basically, we have not covered bubbling and cancellation DOM Events with LiveView.

Options:

  • Take a single pass through the DOM tree and register event listeners on the source element. Would require removeEventListener as well. Also add data-use-capture to allow event to be called as the Event travels down the DOM tree. Removes window.addEventListener. Does not provide cancellation but does cover bubbling and order of execution. This would require some sort of "state" to hold the element, but could be stored in a WeakMap for weak reference to avoid potential memory issues.
class EventManager {
  init(state) {
    const { element } = state;
    element.addEventListener(...);
  }
  
  reinstall(state) {
    const { element } = state;
    element.addEventListener(...)
  }
}
  • Add documentation for phx- events, including order of DOM events and limitations. Encourage use of phx-hook for scenarios that require bubbling and cancellations.
  • Register websocket msgs from an addEventListener and convert to Elixir structs, order properly on server and call handle_ events based on order. Would require client side code to provide "start" and "end" gates. A "click" then "submit" is a defined series of events. A "click" then a listener on a parent "click" is another series of events. A "click" and a "blur" might be two separate series of events. Possible to be chained and thus cancelled by user Elixir side in handle_event?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment