CustomEvent IE8 支持,如何传递参数?

CustomEvent IE8 support, how to pass the params?

我正在尝试为也支持 IE8 的 CustomEvent 制作一个 polyfill,这就是我想出的:

if (typeof window.CustomEvent === "function") {
  return false;
} else {
  function CustomEvent (eventName, params) {
    params = params || { bubbles: false, cancelable: false, detail: undefined };
    if (document.createEvent) { // IE9, IE10
      var evt = document.createEvent('CustomEvent');
      evt.initCustomEvent(
        eventName,
        params.bubbles,
        params.cancelable,
        params.detail
      );
      return evt;
    } else if (document.createEventObject) { // IE8
      var evt = document.createEventObject();
      evt.eventType = eventName;
    }
  };
  CustomEvent.prototype = window.CustomEvent.prototype;
  window.CustomEvent = CustomEvent;
}

对于 IE8 部分,我如何通过 params?

您可以迭代 params 并将它们分配给事件对象:

var evt = document.createEventObject();
evt.eventType = eventName;

for (var prop in params) {
  evt[prop] = params[prop];
}