简体   繁体   English

Javascript - 试图围绕自定义事件

[英]Javascript - Trying to wrap my head around custom events

I'm trying to get my head around custom events. 我正试图了解自定义事件。 I understand how to register and trigger custom events. 我了解如何注册和触发自定义事件。 However, it seems like its not possible to register truly custom events. 但是,似乎无法注册真正的自定义事件。 Everything has to trace back to a DOM event like click, onload, blur, etc. Or am I wrong? 一切都必须追溯到DOM事件,如点击,上传,模糊等。或者我错了吗?

For example, suppose I have an array. 例如,假设我有一个数组。 I want to register an event that fires when the length of the array changes. 我想注册一个在数组长度发生变化时触发的事件。 To my understanding, I would have to register the event and then create a setInterval timer that checks the current array length against the previously stored length. 根据我的理解,我必须注册该事件,然后创建一个setInterval计时器,它根据先前存储的长度检查当前数组长度。 If the length has changed, I would then need to trigger my custom event from inside the setInterval. 如果长度已经改变,那么我需要从setInterval内部触发我的自定义事件。

Is there a way to register an event for my array and have it fire automatically when the length changes? 有没有办法为我的阵列注册一个事件,并在长度变化时自动激活它?

Custom events are in the W3C spec , but none of the major browsers support them. 自定义事件属于W3C规范 ,但主流浏览器都不支持它们。 This is why several other users have suggested 3rd party libraries. 这就是为什么其他几个用户建议使用第三方库的原因。 Prototype, YUI, JQuery, and most others have these capabilities. Prototype,YUI,JQuery和其他大多数人都具备这些功能。 You can also roll your own . 你也可以自己动手

If you'd like to see what some custom event syntax might look like, you can take a look at this tutorial for Prototype custom events . 如果您想查看某些自定义事件语法的外观,可以查看本教程中的Prototype自定义事件 Some important points: 一些要点:

  • Prototype custom events must be attached to DOM elements, so that they can bubble like native events. 原型自定义事件必须附加到DOM元素,以便它们可以像本机事件一样冒泡。
  • They must be in a prefix:event syntax in order to fire 它们必须使用prefix:event语法才能触发
  • They can contain a highly-useful memo parameter that allows any arbitrary context or set of objects to bubble with the event. 它们可以包含一个非常有用的memo参数,该参数允许任意上下文或一组对象与事件一起冒泡。

why don't you write a method addElement for your array that you'll use whenever you want to insert elements,that way you will be able to write code in the event of array.length change. 为什么不为你想要插入元素时使用的数组编写一个方法addElement,这样你就可以在array.length更改的情况下编写代码。 same thing with removeElement. 与removeElement相同的事情。 Events are not meant to be used for this kind of thing. 事件并不意味着用于此类事情。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM