如何解决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 举报,一经查实,本站将立刻删除。