什么是JavaScript中的自定义事件的触发器

什么是JavaScript中的自定义事件的触发器

本文介绍了什么是JavaScript中的自定义事件的触发器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读有关自定义事件的信息,并参考了一些例子。也许我误会了什么是自定义事件,以及它们是如何触发的,并且会感谢一些帮助。

I've been reading about custom events and looked at some examples. Perhaps I am misunderstanding what custom events are and how they are triggered and would appreciate some help.

示例问题

当一个div的背景颜色从一种颜色变化到另一种颜色时触发事件。

To trigger an event when the background colour of a div changes from one colour to another.

情况A)颜色随着脚本中可检测到的用户活动而改变,例如onclick,onmouseover,onkeypress然后我将为这些事件设置一个监听器,并作出相应的响应。这个我理解如何做。

Situation A) The colour changes as result of user activity detectable from within the script, eg by onclick, onmouseover, onkeypress then I would set up a listener for these events and respond accordingly. This I understand how to do.

情况B)颜色随着用户活动的不足而在脚本中被检测到,例如应用于页面的新主题,那么我是否正确地想到以下是必要的?

Situation B) The colour changes as the result of user activity not detectable from within the script, eg a new theme applied to the page, then am I correct in thinking the following are necessary?


  1. 我需要创建一个自定义事件来改变颜色。

  2. 将事件的侦听器添加到相应的DIV

  3. 侦听器需要间隔轮询DIV以检查颜色变化

真的是第3步我不清楚。如果不轮询DIV,事件颜色变化如何触发事件呢?换句话说,脚本如何知道发生了颜色变化?

Really its step 3 I am not clear about. If you are not polling the DIV how does the event colour change trigger an event? In other words how does the script know that a colour change has taken place?

推荐答案

在JavaScript中,自定义事件只是一个消息,广播所有事件听众,说:注意大家:事件X刚刚发生!任何关心该事件的侦听器都可以运行一些功能。

In JavaScript, a custom event is simply a message, broadcast to all event listeners, that says, "Attention everyone: event X just happened!" Any listener that cares about that event can then run some function.

但是,您的自定义事件仍然需要以某种方式被触发。自定义事件不会触发,除非您的代码中的某个地方,您调用(或,在jQuery中)。您的程序必须决定何时触发该事件。如果浏览器本身不会将您可以用作自己的自定义事件的提示的事件触发,那么通常轮询是知道何时触发该事件的唯一方法。

However, your custom event still needs to be fired somehow. Custom events aren't fired unless, somewhere in your code, you call .dispatchEvent (or .trigger, in jQuery). Your program must decide when it is time to fire the event. If the browser doesn't natively fire an event that you can use as a cue for your own custom event, then often polling is the only way to know when to fire the event.

这里的底线是事件只是消息。这取决于你和你写的代码来决定何时触发它们。

The bottom line here is events are just messages. It's up to you and the code you write to decide when to fire them.

这篇关于什么是JavaScript中的自定义事件的触发器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 00:06