tailgo / tailgo.github.io Goto Github PK
View Code? Open in Web Editor NEWMy Site.
My Site.
因为某个需求,在实现时决定使用自定义事件,然后存储事件触发时回调函数的事件参数。
代码类似下面:
var EventSet = [];
var CustomEvent = new Event('custom-event');
$xxxx.addEventListener('custom-event', (event) => { EventSet.push(event); });
$xxxx.dispatchEvent(CustomEvent);
然后测试,没啥毛病。
然后当绑定事件的对象变多了之后,问题来了。
绑定事件的对象变多个之后,事件触发后 EventSet
里面的 Event实例
也会变多,这时候惊奇的发现,EventSet
里面的每个 Event实例
的 target
属性都是最后一个触发事件的元素,作为老油条第一反应肯定是:卧槽,每次触发事件回调的 Event实例
居然都是同一个引用,先修改属性的值再返回,震惊了!。
然后测试了一下原生事件,发现不会出现这个问题。
然后开始了,灵性的猜测这种机制实现时候应该是怎样做的,于是乎实验了一下以下代码:
var CustomEvent = () => new Event('custom-event');
$xxxx.dispatchEvent(CustomEvent());
这次的结果是我们想要的,每个 EventTarget
的值都是触发事件的元素。
于是得到结论,自定义事件触发时是不会多次创建事件对象,而是在第一次创建后就一直在那里,然后在触发时修改对象属性的值,如果我没有遇到这种需要存储事件对象的情况,那么估计都还发现不了这种问题。
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.