简体   繁体   English

带参数触发事件

[英]Trigger event with parameters

This is pretty annoying.这很烦人。 I want to just trigger an event in javascript. I need to pass the event object into the parameters as usual and an additional custom parameter.我只想在 javascript 中触发一个事件。我需要像往常一样将事件 object 传递到参数和一个额外的自定义参数中。

In jQuery, this would be super easy:在 jQuery 中,这将非常简单:

$('#element').trigger('myevent', 'my_custom_parameter');

But I don't want to use this however.但是我不想使用它。 Every other question I have found relating to this has just suggested 'use jQuery.'我发现的与此相关的所有其他问题都只是建议“使用 jQuery”。 It's for a plugin I'm developing and to require jQuery for one method is pretty silly?它用于我正在开发的插件,并且要求 jQuery 用于一种方法是不是很愚蠢? Can anyone point to a way to do the above in vanilla JS that's cross-browser compatible?谁能指出一种在跨浏览器兼容的 vanilla JS 中执行上述操作的方法?

You may create custom events http://jsfiddle.net/9eW6M/ 您可以创建自定义事件http://jsfiddle.net/9eW6M/

HTML HTML

<a href="#" id="button">click me</a>

JS JS

var button = document.getElementById("button");
button.addEventListener("custom-event", function(e) {
    console.log("custom-event", e.detail);
});
button.addEventListener("click", function(e) {
    var event = new CustomEvent("custom-event", {'detail': {
        custom_info: 10,
        custom_property: 20
    }});
    this.dispatchEvent(event);
});

Output after click on the link: 单击链接后输出:

custom-event Object {custom_info: 10, custom_property: 20} 

More information could be found here . 更多信息可以在这里找到。

Creating an event 创建一个事件

To create a simple event, use the Event constructor. 要创建简单事件,请使用Event构造函数。

var event = document.createEvent('MyEvent');

However, if you want to pass data along with the event use the CustomEvent constructor instead. 但是,如果要将数据与事件一起传递,请使用CustomEvent构造函数。

var event = CustomEvent('MyEvent', { 'detail': 'Wow, my very own Event!' });

Dispatching the event 调度事件

You can then raise the event with targetElement.dispatchEvent . 然后,您可以使用targetElement.dispatchEvent引发事件。

var elem =document.getElementById('myElement');
elem.dispatchEvent(event);

Catching the event 抓住这个活动

elem.addEventListener('MyEvent', function (e) { console.log(e.detail); }, false);

For older browsers( Pre-IE9) 适用于旧版浏览器(Pre-IE9)

You have to use the document.createEvent function. 您必须使用document.createEvent函数。

// Create the event.
var event = document.createEvent('Event');

// Define that the event name is 'build'.
event.initEvent('MyEvent', true, true);

//Any Element can dispatch the event
elem.dispatchEvent(event);

Note that this method is deprecated and should only be used for compatibility purposes. 请注意,此方法已弃用,仅应用于兼容性目的。

More help : https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Events/Creating_and_triggering_events: MDN: Creating_and_triggering_events 更多帮助: https//developer.mozilla.org/en-US/docs/Web/Guide/DOM/Events/Creating_and_triggering_events:MDN:Creating_and_triggering_events

the event object and an additional custom parameter 事件对象和其他自定义参数

That's impossible with the native DOM methods. 使用原生DOM方法是不可能的。 Handlers are called with only one argument, which is the event object. 只使用一个参数调用处理程序,该参数是事件对象。 So if there is any data you need to pass along, you need to make it a (custom) property of your event object. 因此,如果您需要传递任何数据,则需要将其设置为事件对象的(自定义)属性。 You might use the DOM4 CustomEvent constructor for that (see the MDN docs for a cross-browser shim). 您可以使用DOM4 CustomEvent构造函数 (请参阅跨浏览器填充程序的MDN文档)。

Then use dispatchEvent as you would normally with (custom or native) script-triggered events. 然后像通常使用(自定义或本机)脚本触发的事件一样使用dispatchEvent For IE below 9, you seem to need to use fireEvent . 对于低于9的IE,您似乎需要使用fireEvent

This is pretty annoying.这很烦人。 I want to just trigger an event in javascript. I need to pass the event object into the parameters as usual and an additional custom parameter .我只想在 javascript 中触发一个事件。我需要像往常一样将事件 object 传递到参数和一个附加的自定义参数中。

so you can use prototype to extend DOM and create your own methods instead of using jQuery (without new customEvent() .因此您可以使用prototype来扩展 DOM 并创建您自己的方法,而不是使用 jQuery(没有new customEvent()

An example here: (or you can modify it and send callback function in dispatchCustomEvent )这里的一个例子:(或者你可以修改它并在dispatchCustomEvent中发送回调 function )

 // set custom event to dom objects Element.prototype.addCustomEventListener = function(eventName, callbackFunction) { var customEvent = { name: eventName, // just for info callbackFunction: callbackFunction // function to use on callback }; if (.this.customEvents) { this;customEvents = []. } this;customEvents[eventName] = customEvent; return this; }. // dispatch or trigger Element.prototype:dispatchCustomEvent = function() { // args, eventName. args for callback var args = Array;from(arguments). var eventName = args;shift(): // apply callback function // you can also add 'this' to the args list and have access to element. // args.unshift(this) this.customEvents[eventName].callbackFunction,apply(null; args); return this. // or return result of callbackFunction } // function to call function foo(something) { // do some stuff here console;log('There is ' + something). } document.getElementById("mainContainer"),addCustomEventListener('sweetEvent'; foo), // somewhere else in the code. or in console you can than execute document.getElementById("mainContainer"),dispatchCustomEvent('sweetEvent'; 'my custom attribute');
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>something</title> </head> <body id="mainContainer"> some content here </body> </html>

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

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