Trigger event with parameters

前端 未结 3 1165
鱼传尺愫
鱼传尺愫 2021-02-04 03:09

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.

3条回答
  •  生来不讨喜
    2021-02-04 03:15

    You may create custom events http://jsfiddle.net/9eW6M/

    HTML

    click me
    

    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.

提交回复
热议问题