假设我有这样的滚动/滚轮事件:
container.addEventListener("wheel", (e) => {
const isScrollingDown = Math.sign(e.wheelDeltaY);
// call some function once, don't listen for wheel event anymore
// then listen for event again when done
}
基于deltaY,我检测到用户是向下滚动还是向上滚动。当我检测到该函数(立即),立即删除事件侦听器并在函数完成后再次侦听该函数时,如何调用它一次?
我无法从事件监听器中删除事件监听器吗?
谢谢。
答案 0 :(得分:2)
您可以使用removeEventListener()
功能。 documentation
示例:
let wheelHandler = function(e) {
toggleListener(wheelHandler, false)
const isScrollingDown = Math.sign(e.wheelDeltaY);
// call some function once, don't listen for wheel event anymore
// then listen for event again when done
toggleListener(wheelHandler, true)
};
let toggleListener = function(listener, add) {
if (add) {
container.addEventListener("wheel", wheelHandler)
} else {
container.removeEventListener("wheel", wheelHandler)
}
}
toggleListener(wheelHandler, true);
答案 1 :(得分:1)
您可以定义加载变量并在每次运行功能之前进行检查
public class ProductService : IProductService
{
private readonly IAsyncRepository<Product> _productRepository;
private readonly IAsyncRepository<ProductCategory> _productCategoryRepository;
public ProductService(
IAsyncRepository<Product> productRepository,
IAsyncRepository<ProductCategory> productCategoryRepository)
{
_productRepository = productRepository;
_productCategoryRepository = productCategoryRepository;
}
public async Task CreateProductAsync(string name, string allergens, int productCategoryId)
{
var category = await _productCategoryRepository.FindByIdAsync(productCategoryId);
var product = new Product(name, allergens, category);
await _productRepository.AddAsync(product);
}
}
答案 2 :(得分:1)
在第一个滚轮之后等待1秒:
function handleWheel(e){
console.log(Math.random())
document.getElementById("container").removeEventListener("wheel", handleWheel)
setTimeout(()=>{
document.getElementById("container").addEventListener("wheel", handleWheel);
},1000); // return event after 1 second
}
document.getElementById("container").addEventListener("wheel", handleWheel)
<div id="container" >wheel</div>