我想在不同的场合分派 CustomEvent。网络上的大多数示例只创建和分派 CustomEvents 一次。我想知道如何正确地做到这一点。
在这个例子中,“A-Button”一遍又一遍地分派相同的事件。“B-Button”new CustomEvent每次创建一个,应该调度事件。
var targetA = document.getElementById('targetA');
var targetB = document.getElementById('targetB');
var evtA = new CustomEvent("myEvent");
function a(){
targetA.dispatchEvent(evtA);
}
function b(){
targetB.dispatchEvent(new CustomEvent("myOtherEvent"));
}
targetA.addEventListener("myEvent", function(e){
console.log(e);
console.log(e.timeStamp);
});
targetB.addEventListener("myOtherEvent", function(e){
console.log(e);
console.log(e.timeStamp);
});Run Code Online (Sandbox Code Playgroud)
<button onclick="a()">A</button>
<button onclick="b()">B</button>
<div id="targetA"></div>
<div id="targetB"></div>Run Code Online (Sandbox Code Playgroud)
A 方法的副作用可能是时间戳未更新。这可能会导致依赖时间戳的处理程序出现意外行为。
B 方法的性能可能较低,因为 CustomEvent 对象被一遍又一遍地实例化。(内存应该不是问题。)
有没有“正确”的方法,或者有什么最佳实践?
我想为使用requestAnimationFrame和的模块编写一个开玩笑的单元测试cancelAnimationFrame。
我尝试用我自己的模拟覆盖 window.requestAnimationFrame(如本答案中所建议的那样),但该模块继续使用 jsdom 提供的实现。
我目前的方法是使用requestAnimationFrame来自 jsdom的(以某种方式)内置实现,它似乎在幕后使用setTimeout,应该可以通过使用jest.useFakeTimers().
jest.useFakeTimers();
describe("fakeTimers", () => {
test.only("setTimeout and trigger", () => {
const order: number[] = [];
expect(order).toEqual([]);
setTimeout(t => order.push(1));
expect(order).toEqual([]);
jest.runAllTimers();
expect(order).toEqual([1]);
});
test.only("requestAnimationFrame and runAllTimers", () => {
const order: number[] = [];
expect(order).toEqual([]);
requestAnimationFrame(t => order.push(1));
expect(order).toEqual([]);
jest.runAllTimers();
expect(order).toEqual([1]);
});
});
Run Code Online (Sandbox Code Playgroud)
第一次测试成功,第二次失败,因为order是空的。
测试依赖于requestAnimationFrame(). 特别是如果我需要测试帧被取消的条件?