Liveview javascript pushEvent to myself, not the parent liveview?

I have a CreateLive liveview, that has a FormComponent component. In my form component I’m doing some drag and drop and want to send the event to the FormComponent.

Right now the event is being send to the parent CreateLive liveview.

How can I send the event to the FormComponent?

// in my javascript hook
let MyHookName = {
  mounted() {
    let element = this.el;
    this.pushEvent("my_event_name", { values: ids });
  }
};

export default MyHookName;

pushEventTo is your friend. Use the DOM id of the element with the hook on it as the target/to.

import Sortable from "sortablejs"; 
  
 const Drag = { 
   mounted() { 
     const hook = this; 
     const id = "#" + this.el.id; 
  
     document.querySelectorAll(`${id} .dropzone`).forEach((dropzone) => { 
       new Sortable(dropzone, { 
         animation: 200, 
         delay: 50, 
         delayOnTouchOnly: true, 
         direction: "vertical", 
         group: "shared", 
         draggable: ".draggable", 
         ghostClass: "sortable-ghost", 
         onEnd: function (evt) { 
           hook.pushEventTo(id, "dropped", { 
             draggedId: evt.item.id, // id of the dragged item 
             dropzoneId: evt.to.id, // id of the drop zone where the drop occured 
             draggableIndex: evt.newDraggableIndex, // index where the item was dropped (relative to other items in the drop zone) 
           }); 
         }, 
       }); 
     }); 
   }, 
 }; 
  
 export default Drag;
3 Likes

Maybe I can pass @myself to the Hook, and then use pushEventTo in the Javascript? Hmmm

Edit: posted at the same time thanks will try this!

Edit 2: That worked, thanks!

For future readers, pushEventTo also supports passing the node element e.g. this.el instead of selector e.g. "#" + this.el.id as the first parameter for target.

5 Likes

Your note was merged into the docs. Add note to push event to by user20230119 · Pull Request #3099 · phoenixframework/phoenix_live_view · GitHub

4 Likes