JS自定义事件触发2次

问题描述

我快要疯了,试图弄清楚到底发生了什么。实际上,我有一个使用 shared.js 文件的 angular v9 应用程序,我在其中存储了一些与部分静态前端共享的函数。在某个时刻,我从 angular 应用程序开始调用 addToCart () 函数。许多操作中的此函数的任务是发出 onAddToCart 事件以执行其他 UI 更新操作。我还有其他类似的调用(例如登录),它们工作正常,但这个没有。

ANGULAR COMPONENT HTML
<button (click)="addProductToCart(product)">Add</button>

ANGULAR COMPONENT TS
declare function addToCart(request): any;
-----
addProductToCart(product: Product): void {
  addToCart(product);
}

SHARED.JS
function addToCart(product) {
...
dispatchEventAddToCart(cartItem);
}

function dispatchEventAddToCart(cartItem) {
  const addToCart = new CustomEvent('onAddToCart',{
    detail: cartItem
  });
  window.dispatchEvent(addToCart);
}

(() => {
  refreshCartCounter();
  window.addEventListener('onAddToCart',(e) => {
    refreshCartCounter();
    console.log('add to cart executed'); <= I see two log always!
  });
})();
ANGULAR COMPONENT TEMPLATE
<div>
    <table class="table table-bordered table-hover">
           <thead>
              <tr>
              <th scope="col">Prodotto</th>
              <th scope="col">SKU</th>
              <th scope="col">Descrizione</th>
              <th scope="col">Categoria</th>
              <th scope="col">marca</th>
              <th scope="col">Preventivo</th>
             </tr>
             </thead>
            <tbody *ngIf="productFindResponse">
            <tr *ngFor="let product of productFindResponse.products">
              <td>
                <figure class="media">
                   <img src="{{ product.image}}" class="rounded img-thumbnail img-sm" #img (error)="img.src = getDefaultimage()" alt="{{ product.sku }} - {{ product.description }}">
                </figure>
                </td>
                <td><a href="{{ product.skunorm }}">{{ product.sku }}</a></td>
                <td>{{ product.description }}</td>
                <td>{{ product.category.name }}</td>
                <td>{{ product.brand.name }}</td>
                <td>
                <button type="button" class="btn btn-primary" (click)="addProductToCart(product)"> Add <i class="fas fa-cart-plus"></i>
                </button>
             </td>
         </tr>
     </tbody>
  </table>
</div>

我做错了什么? 我试图设置bubble = false但结果是一样的..

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)