简体   繁体   English

点亮元素,在组件外部单击时关闭下拉菜单

[英]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.我正在使用 Lit Element,我正在尝试在“单击”上添加一个事件侦听器,该侦听器将设置一个变量 state,它将下拉列表设置为展开或不展开。 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: fct逻辑:

  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 :我渲染的 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.重要说明:我希望在所有 window 上监听点击事件,而不仅仅是组件本身。 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. PS:我不知道为什么 e.currentTaget.className 没有给我实际的类名,但结果是未定义的。

When you use removeEventListener you have to pass a reference to the same function you used when adding the listener.当您使用removeEventListener时,您必须传递对添加侦听器时使用的相同 function 的引用。

In this example the function is stored in fn .在此示例中,function 存储在fn中。 (You might have to change the this reference here, it depends a bit on your whole component). (您可能必须在此处更改this引用,这在一定程度上取决于您的整个组件)。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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