简体   繁体   中英

Lit element, close drop down when click outside of component

I'm working with Lit Element and I'm trying add an event listener on 'Click' that will a variable state that will set the dropdown to be expand or not. But once the drop down is 'closed' I want to remove that event to avoid unnecessary event calls on 'Click.

Adding the event works great but I cannot remove it.

Here is the idea:

  public willUpdate(changedProps: PropertyValues) {
    super.willUpdate(changedProps);

    if (changedProps.has("_tenantsExpanded")) {
      document.removeEventListener("click", (ev) => this._eventLogic(ev, this));

      if (this._tenantsExpanded)
        document.addEventListener("click", (ev) => this._eventLogic(ev, this));
    }
  }

The fct logic:

  private _eventLogic(e: MouseEvent, component: this) {
    const targets = e.composedPath() as Element[];
    if (!targets.some((target) => target.className?.includes("tenant"))) {
      component._tenantsExpanded = false;
    }
  }

Code in my render's function :

 ${this._tenantsExpanded
     ? html` <div class="tenants-content">${this._tenantsContent()}</div> `
     : html``}

Important note : I want the click event to be listened on all the window, not just the component itself. The same for removing the event.

PS: I don't know why e.currentTaget.className doesn't give me the actual className, but results to an undefined.

When you use removeEventListener you have to pass a reference to the same function you used when adding the listener.

In this example the function is stored in fn . (You might have to change the this reference here, it depends a bit on your whole component).

const fn = (ev) => this._eventLogic(ev, this);

document.addEventListener("click", fn);
document.removeEventListener("click", fn);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM