事件侦听
创建自定义事件
可以使用Event构造函数创建事件,如下所示:
var event = new Event('build');
// Listen for the event.
elem.addEventListener('build', function (e) { /* ... */ }, false);
// Dispatch the event.
elem.dispatchEvent(event);
大多数现代浏览器都支持此构造函数(Internet Explorer是例外)。有关更详细的方法(适用于Internet Explorer),请参阅下面的老式方法。
添加自定义数据 - CustomEvent()
要向事件对象添加更多数据,存在CustomEvent接口,detail属性可用于传递自定义数据。
例如,可以按如下方式创建事件:
var event = new CustomEvent('build', { detail: elem.dataset.time });
这将允许您访问事件侦听器中的其他数据:
function eventHandler(e) {
console.log('The time is: ' + e.detail);
}
事件冒泡
理解事件的冒泡机制对事件的触发和捕获的恰当应用有帮助。通常需要从子元素触发事件,并让祖先捕获它;可选地,使用数据:
<form>
<textarea></textarea>
</form>
const form = document.querySelector('form');
const textarea = document.querySelector('textarea');
// Create a new event, allow bubbling, and provide any data you want to pass to the "details" property
const eventAwesome = new CustomEvent('awesome', {
bubbles: true,
detail: { text: () => textarea.value }
});
// The form element listens for the custom "awesome" event and then consoles the output of the passed text() method
form.addEventListener('awesome', e => console.log(e.detail.text()));
// As the user types, the textarea inside the form dispatches/triggers the event to fire, and uses itself as the starting point
textarea.addEventListener('input', e => e.target.dispatchEvent(eventAwesome));
创建和动态调度的事件
元素可以侦听尚未创建的事件:
const form = document.querySelector('form');
const textarea = document.querySelector('textarea');
form.addEventListener('awesome', e => console.log(e.detail.text()));
textarea.addEventListener('input', function() {
// Create and dispatch/trigger an event on the fly
// Note: Optionally, we've also leveraged the "function expression" (instead of the "arrow function expression") so "this" will represent the element
this.dispatchEvent(new CustomEvent('awesome', { bubbles: true, detail: { text: () => textarea.value } }))
});
触发内置事件
此示例演示如何使用DOM方法模拟复选框上的单击(以编程方式生成单击事件)。
function simulateClick() {
var event = new MouseEvent('click', {
view: window,
bubbles: true,
cancelable: true
});
var cb = document.getElementById('checkbox');
var cancelled = !cb.dispatchEvent(event);
if (cancelled) {
// A handler called preventDefault.
alert("cancelled");
} else {
// None of the handlers called preventDefault.
alert("not cancelled");
}
}
内存泄露
内存泄露案例
在echarts的resize的场景中,可以看到网上提供的解决方案(普通场景木问题,部分场景会造成内存泄露,取决于你的框架代码的实现):
myChart.setOption(option);
window.addEventListener("resize", function () {
myChart.resize();
});
如果事件绑定在window上,这些变量生命周期就会随着页签一直存在,一直在内存当中。如果不停的重新加载和刷新(子页面),就会造成内存泄露。正确姿势如下:
在初始化页面的时候注册一下
function resizeEcharts(){
//$box.find('[data-toggle="echarts"]') 获取echarts的容器
$box.find('[data-toggle="echarts"]').each(function(){
var element = $(this)[0];
echarts. getInstanceByDom(element).resize();
})
}
window.addEventListener("resize",resizeEcharts);
捕获事件
- 捕获事件中最好不要含有局部变量,否则这个变量将一直驻留在内存中
- 捕获函数,注意注册匿名函数,防止重复注册