Skip to content

Instantly share code, notes, and snippets.

@nclsjstnn
Last active December 12, 2018 03:27
Show Gist options
  • Save nclsjstnn/3182d5f8a2dba434961a864d4e41212b to your computer and use it in GitHub Desktop.
Save nclsjstnn/3182d5f8a2dba434961a864d4e41212b to your computer and use it in GitHub Desktop.
Event and CustomEvent ES6 polyfill solution for IE11
const eventPolyfill = () => {
if (typeof window.Event === 'function') {
return false;
}
const Event = (event) => {
const evt = document.createEvent('Event');
evt.initEvent(event, true, true);
return evt;
};
Event.prototype = window.Event.prototype;
window.Event = Event;
return true;
};
const customEventPolyfill = () => {
if (typeof window.CustomEvent === 'function') {
return false;
}
const CustomEvent = (event, params) => {
const eventParams = params || {
bubbles: false,
cancelable: false,
detail: undefined,
};
const evt = document.createEvent('CustomEvent');
evt.initCustomEvent(event, eventParams.bubbles, eventParams.cancelable, eventParams.detail);
return evt;
};
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent;
return true;
};
export default () => {
eventPolyfill();
customEventPolyfill();
};
import eventsPolyfill from './eventsPolyfill';
describe('eventsPolyfill.js', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('should do nothing if the browser supports Events/CustomEvent', () => {
const event = jest.fn();
const customEvent = jest.fn();
global.window = {
CustomEvent: customEvent,
Event: event,
};
eventsPolyfill();
expect(global.window.Event).toBe(event);
expect(global.window.CustomEvent).toBe(customEvent);
});
it('should pollyfill Event/CustomEvent if the browser (IE11) does not support them', () => {
global.window = {
CustomEvent: 'I am IE9 and i succ',
Event: 'I am IE9 and i succ',
};
eventsPolyfill();
expect(global.window.Event).toBeInstanceOf(Function);
expect(global.window.CustomEvent).toBeInstanceOf(Function);
});
it('should assign evt object to Event', () => {
const evt = {
initEvent: jest.fn(),
};
global.window = {
CustomEvent: 'I am IE9 and i succ',
Event: 'I am IE9 and i succ',
};
global.document = {
createEvent: jest.fn().mockReturnValue(evt),
};
eventsPolyfill();
expect(global.window.Event('My shinny event')).toBe(evt);
});
it('should assign evt object to CustomEvent', () => {
const evt = {
initCustomEvent: jest.fn(),
};
global.window = {
CustomEvent: 'I am IE9 and i succ',
Event: 'I am IE9 and i succ',
};
global.document = {
createEvent: jest.fn().mockReturnValue(evt),
};
eventsPolyfill();
expect(global.window.CustomEvent('SomeEvent.changed', { detail: 'some detail' })).toBe(evt);
});
});
import eventsPolyfill from './eventsPolyfill';
eventsPolyfill();
@nclsjstnn
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment