简体   繁体   English

定义自定义事件

[英]Define custom event

I wanna learn how to define a custom event , but not exactly as it is said over the net! 我想学习如何定义一个自定义事件 ,但不完全像在网上说的那样! let me illustrate: 让我说明一下:

In the jQuery Website in the part Introducing Custom Events it teaches you how to create a custom event in your code: 在jQuery网站的“自定义事件介绍 ”部分中,它教您如何在代码中创建自定义事件:

eg 例如

$(document).on('myEvent',function(){
    alert('Hello World');
});

then on an event, you'll call: 然后在一个事件上,你会打电话给:

$(document).trigger('myEvent');

Well, no problem until here. 好吧,直到这里没问题。 to go further I have to give you another example: 为了更进一步,我必须再给你一个例子:

The Question: 问题:

let's say we've defined: 让我们说我们定义了:

$.fn.myEvent=function(callback){
    $(document).bind('contextmenu',this,callback);
};

so we can use it as: 所以我们可以用它作为:

$(document).myEvent(function(){
    alert('Hello World');
});

my question here is, how can we define "myEvent" so that we can use it as: 我的问题是,我们如何定义“myEvent”以便我们可以将其用作:

$(document).on('myEvent',function(){
    alert('Hello World');
});

with the functionality of the $(document).myEvent(); 具有$(document).myEvent(); so that we can pass a callback function to it without needing to actually trigger the event? 这样我们就可以将回调函数传递给它而无需实际trigger事件?

More Explanation: 更多说明:

for example, when we call $(document).on('click'); 例如,当我们调用$(document).on('click'); we don't actually need to trigger the click event elsewhere like $(document).trigger('click') in order to get it to work, so whenever click happens the function fires. 我们实际上并不需要在其他地方触发click事件,例如$(document).trigger('click')以使其工作,因此每当click发生时该函数都会触发。 I wanna have an event listener for "myEvent" so that when the conditions are matched, the function fires. 我想为“myEvent”设置一个事件监听器,以便在条件匹配时触发该函数。

In another word (as mentioned below in the comments), I wanna know if there's a way to let jQuery treat "myEvent" as if it is one of the default events (click, mousemove, submit, etc). 换句话说(如下面评论中所述),我想知道是否有办法让jQuery将“myEvent”视为默认事件之一(click,mousemove,submit等)。

Any answer or idea is highly appreciated. 任何答案或想法都非常感谢。

I wanna have an event listener for "myEvent" so that when the conditions are matched, the function fires. 我想为“myEvent”设置一个事件监听器,以便在条件匹配时触发该函数。

How would the engine know what "conditions" you mean? 引擎如何知道你的意思是什么“条件”? No, "custom events" are called custom because they are not natively trigged (through some lower-level action), but by custom code. 不,“自定义事件”被称为自定义,因为它们不是通过本地触发(通过某些较低级别的操作),而是通过自定义代码。
You may trigger a custom event whenever you see the condition matched that you're looking for. 只要看到匹配的条件,就可以触发自定义事件。

About the definition of $.fn.myEvent , you might want to have a look at how the shortcuts for native events are created (where name would be "myEvent" ). 关于$.fn.myEvent的定义,您可能想要了解如何创建本机事件的快捷方式 (其中name将是"myEvent" )。

You're lumping together two different points: 你把两个不同点混为一谈:

  1. how events work on general, and 事件如何发挥作用,以及
  2. how a browser environment dispatches events related to user action. 浏览器环境如何调度与用户操作相关的事件

For the first point, I'll quote from another answer of mine : 首先,我将引用我的另一个答案

In JavaScript, a custom event is simply a message, broadcast to all event listeners, that says, "Attention everyone: event X just happened!" 在JavaScript中,自定义事件只是一条消息,向所有事件监听器广播,表示“注意每个人:事件X刚刚发生!” Any listener that cares about that event can then run some function. 任何关心该事件的侦听器都可以运行某些功能。

That's how events work in JavaScript. 这就是事件在JavaScript中的工作方式。 You set up listeners, and later something triggers the event. 您设置了侦听器,稍后会触发事件。 The trigger acts as a message to the listeners, telling them to run. 触发器充当听众的消息,告诉他们运行。

I've just said something triggers an event: we'll call that thing the initiator of the event. 我刚刚说了一些触发事件的事情:我们称之为事件的发起者 With custom events, the initiator is always other JavaScript code that you write (or that comes from a library, etc.). 对于自定义事件,启动程序始终是您编写的其他JavaScript代码(或来自库等的代码)。 However, with native events the initiator is the browser itself . 但是,对于本机事件,启动器是浏览器本身 There is no way for JavaScript to control how the browser chooses to dispatch events. JavaScript无法控制浏览器选择分派事件的方式。

The best you can do is listen for native browser events and then have those listeners dispatch custom events themselves. 您可以做的最好的事情是侦听本机浏览器事件,然后让这些侦听器自己调度自定义事件。

For people who are wondering (like I did in the last 2 years) you can create a custom event (using pure javascript) as explained below: 对于那些想知道的人(就像我在过去两年中所做的那样),你可以创建一个自定义事件(使用纯javascript),如下所述:

var myEvent = new Event('myEvent');

and then you can use it like this: 然后你可以像这样使用它:

document.querySelector('button').addEventListener(myEvent, function () {});

Simple Usage Example DEMO 简单用法示例 DEMO

Let's say we have a variable called bgColor and we want to change background color of 5 buttons, color of a paragraph and border color of an input anytime the bgColor value changes AND we don't want to use an interval to check on the value change and we also don't want to repeat the same code over and over again anytime the variable changes. 假设我们有一个名为bgColor的变量,我们想要在bgColor值改变的任何时候改变5个按钮的背景颜色,段落的颜色和输入的边框颜色,我们不想使用间隔来检查值的变化我们也不想在变量发生变化时反复重复相同的代码。

First we need to define our variables: 首先,我们需要定义变量:

var bgColor='red',
    eventName = 'bgColorChanged';

Then we need to listen for the event: 然后我们需要听取这个事件:

function Listen(elems,eventName,callback){

    var event=new Event(eventName); //create the custom event

    for(var i=0, elemsLength=elems.length; i < elemsLength; i++){ //iterate over the selected elements

        elems[i].addEventListener(event,callback); //add event listener for our custom event

        elems[i][eventName]=event; //store the event

        //store the element
        if(window.affectedElems){
            window.affectedElems.push(elems[i])
        }
        else{
            window.affectedElems=[];
            window.affectedElems.push(elems[i])
        }
        //----------------------------

    }
}

Now we can listen for our custom event like this: 现在我们可以像这样收听我们的自定义事件:

Listen(document.querySelectorAll('button'),eventName,function(){
    this.style.backgroundColor=bgColor;
});

Then we need a function to Dispatch/Fire our Event: 然后我们需要一个函数来Dispatch / Fire我们的事件:

function dispatchEvent(eventName) {

    var event=document.createEvent("HTMLEvents"), //defining the type of the event

    elems=window.affectedElems; //getting the stored elements

    //iterating over each element and dispatching the stored event
    for(var i=0, elemsLength=elems.length; i < elemsLength; i++){
        event.initEvent(elems[i][eventName], true, true);
        event.eventName = eventName;
        elems[i].dispatchEvent(event);
    }
    //-----------------------------------
}

Now we can fire our event like this: 现在我们可以像这样开火我们的活动:

dispatchEvent(eventName);

Now that everything's ready we just need to change the value of bgColor and just fire the event and let our system do the work. 现在一切准备就绪,我们只需要更改bgColor的值, bgColor事件并让我们的系统完成工作。

bgColor='blue';
dispatchEvent(eventName);

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

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