customevent
JavaScript events have been the gateway to user interaction within the browser since its inception. Not only do events tell us when an interaction happens, but events tell us type of interaction, the nodes involved, and provide us methods for working with the event. Creating custom events and triggering them have always been trickier. Using JavaScript's CustomEvent API, that trickery can be eliminated. The CustomEvent API allows developers to not only create custom events but trigger them on DOM nodes, passing data along the way. Best of all, the API is super simple!
自事件发生以来,JavaScript事件一直是浏览器内用户交互的网关。 事件不仅告诉我们何时发生交互,而且事件告诉我们交互的类型,所涉及的节点,并为我们提供处理事件的方法。 创建自定义事件并触发它们一直很棘手。 使用JavaScript的CustomEvent API,可以消除这种麻烦。 CustomEvent API使开发人员不仅可以创建自定义事件,而且可以在DOM节点上触发自定义事件,并一路传递数据。 最棒的是,API非常简单!
When working with customizing events, there's two components included in an event being "custom": a custom event name and the ability to trigger that event. Adding an event listener to an element, however, stays the same:
使用自定义事件时,事件中包含“自定义”的两个组件:自定义事件名称和触发该事件的功能。 但是,将事件侦听器添加到元素的过程保持不变:
myElement.addEventListener("userLogin", function(e) { console.info("Event is: ", e); console.info("Custom data is: ", e.detail); })Here we've added a userLogin event, just as easily as we could add a native mouseover or focus event -- that's not special. The special part is creating and triggering the event:
在这里,我们添加了userLogin事件,就像添加本机鼠标悬停或焦点事件一样容易-这并不特殊。 特殊的部分是创建和触发事件:
// First create the event var myEvent = new CustomEvent("userLogin", { detail: { username: "davidwalsh" } }); // Trigger it! myElement.dispatchEvent(myEvent);The CustomEvent constructor allows for creation of the custom event, allowing you to pass both a custom event name as well as a number of special properties; dispatchEvent triggers the event on the given element. Let's make the event to be triggered super-customized by configuring its bubbling, cancelable, detail properties:
CustomEvent构造函数允许创建自定义事件,从而允许您传递自定义事件名称以及许多特殊属性。 dispatchEvent在给定元素上触发事件。 通过配置事件的冒泡,可取消的详细信息属性,使事件被超级定制:
var myEvent = new CustomEvent("userLogin", { detail: { username: "davidwalsh" }, bubbles: true, cancelable: false });Creating and trigger custom events with custom data is incredibly useful. Not only can you create your own naming convention for events, but you may also pass custom data along the way! You can keep up with browser support on the CustomEvent API on MDN, but this API is available in most modern browsers.
使用自定义数据创建和触发自定义事件非常有用。 您不仅可以为事件创建自己的命名约定,而且还可以沿途传递自定义数据! 您可以在MDN上的CustomEvent API上保持对浏览器的支持,但是大多数现代浏览器都提供此API。
翻译自: https://davidwalsh.name/customevent
customevent
相关资源:jdk-8u281-windows-x64.exe