Code Monkey home page Code Monkey logo

tailgo.github.io's Introduction

Hi there 👋

tailgo's GitHub stats

tailgo.github.io's People

Contributors

dependabot[bot] avatar tailgo avatar

Watchers

 avatar  avatar  avatar

tailgo.github.io's Issues

Event 对象分析

记录一次在使用自定义事件时候遇到的坑

背景

因为某个需求,在实现时决定使用自定义事件,然后存储事件触发时回调函数的事件参数。

代码类似下面:

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 的值都是触发事件的元素。

于是得到结论,自定义事件触发时是不会多次创建事件对象,而是在第一次创建后就一直在那里,然后在触发时修改对象属性的值,如果我没有遇到这种需要存储事件对象的情况,那么估计都还发现不了这种问题。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.