CustomEvent自定义事件

javascript与HTML之间的交互是通过事件来实现的。事件,就是文档或浏览器窗口发生的一些特定的交互瞬间。通常大家都会认为事件是在用户与浏览器进行交互的时候触发的,其实通过javascript我们可以在任何时刻触发特定的事件,并且这些事件与浏览器创建的事件是相同的。

通过createEvent方法,我们可以创建新的Event对象,这个方法接受一个参数eventType,即想获取的Event对象的事件模板名,其值可以为HTMLEvents、MouseEvents、UIEvents以及CustomEvent(自定义事件)。这里我们将以CustomEvent为例子进行讲解。

首先创建自定义事件对象

var event = document.createEvent("CustomEvent");

然后初始化事件对象

event.initCustomEvent(in DOMString type, in boolean canBubble, in boolean cancelable, in any detail);

其中,第一个参数为要处理的事件名
第二个参数为表明事件是否冒泡
第三个参数为表明是否可以取消事件的默认行为
第四个参数为细节参数
例如:event.initCustomEvent("test", true, true, {a:1, b:2}) 表明要处理的事件名为test,事件冒泡,可以取消事件的默认行为,细节参数为一个对象{a:"test", b:"success"}
最后触发事件对象

document.dispatchEvent(event);

当然我们需要定义监控test事件的处理程序

document.addEventListener("test", function(e){
    var obj = e.detail;
    alert(obj.a + "  " + obj.b);
});

最后会弹出框显示"test success"
但不是所有的浏览器都支持,尤其是移动端,下面分享一个封装好的函数,来解决:

(function() {
    if (typeof window.CustomEvent === 'undefined') {
        function CustomEvent(event, params) {
            params = params || {
                bubbles: false,
                cancelable: false,
                detail: undefined
            };
            var evt = document.createEvent('Events');
            var bubbles = true;
            for (var name in params) {
                (name === 'bubbles') ? (bubbles = !!params[name]) : (evt[name] = params[name]);
            }
            evt.initEvent(event, bubbles, true);
            return evt;
        };
        CustomEvent.prototype = window.Event.prototype;
        window.CustomEvent = CustomEvent;
    }
})();

触发如下:

document.dispatchEvent(event);

还有另外两种写法,下面来分享一下:

1)

if (!window.CustomEvent) {
        window.CustomEvent = function(type, config) {
            config = config || { bubbles: false, cancelable: false, detail: undefined};
            var e = document.createEvent('CustomEvent');
            e.initCustomEvent(type, config.bubbles, config.cancelable, config.detail);
            return e;
        };
        window.CustomEvent.prototype = window.Event.prototype;
    }

2)
(function () {
  if ( typeof window.CustomEvent === "function" ) return false; //If not IE

  function CustomEvent ( event, params ) {
    params = params || { bubbles: false, cancelable: false, detail: undefined };
    var evt = document.createEvent( 'CustomEvent' );
    evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
    return evt;
   }

  CustomEvent.prototype = window.Event.prototype;

  window.CustomEvent = CustomEvent;
})();
 

触发的时候,把触发封装到一个函数中:

var dispatch = function(event) {
        var e = new CustomEvent(event, {
            bubbles: true,
            cancelable: true
        });
        //noinspection JSUnresolvedFunction
        window.dispatchEvent(e);
 };


链接:http://www.jianshu.com/p/1cf1c80c0586
https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent

posted @ 2017-08-26 15:08  方帅  阅读(3596)  评论(0编辑  收藏  举报