Skip to content

Commit

Permalink
fix: support node and other non-browser environments
Browse files Browse the repository at this point in the history
  • Loading branch information
shrpne authored and Kumar Harsh committed May 15, 2018
1 parent 9935c2f commit ddf42a6
Showing 1 changed file with 45 additions and 39 deletions.
84 changes: 45 additions & 39 deletions custom-event-polyfill.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,46 +4,52 @@
// https://github.com/d4tocchini/customevent-polyfill
// https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill

try {
var ce = new window.CustomEvent('test', { cancelable: true });
ce.preventDefault();
if (ce.defaultPrevented !== true) {
// IE has problems with .preventDefault() on custom events
// http://stackoverflow.com/questions/23349191
throw new Error('Could not prevent default');
(function() {
if (!window) {
return;
}
} catch (e) {
var CustomEvent = function(event, params) {
var evt, origPrevent;
params = params || {
bubbles: false,
cancelable: false,
detail: undefined
};

evt = document.createEvent('CustomEvent');
evt.initCustomEvent(
event,
params.bubbles,
params.cancelable,
params.detail
);
origPrevent = evt.preventDefault;
evt.preventDefault = function() {
origPrevent.call(this);
try {
Object.defineProperty(this, 'defaultPrevented', {
get: function() {
return true;
}
});
} catch (e) {
this.defaultPrevented = true;
}
try {
var ce = new window.CustomEvent('test', { cancelable: true });
ce.preventDefault();
if (ce.defaultPrevented !== true) {
// IE has problems with .preventDefault() on custom events
// http://stackoverflow.com/questions/23349191
throw new Error('Could not prevent default');
}
} catch (e) {
var CustomEvent = function(event, params) {
var evt, origPrevent;
params = params || {
bubbles: false,
cancelable: false,
detail: undefined
};

evt = document.createEvent('CustomEvent');
evt.initCustomEvent(
event,
params.bubbles,
params.cancelable,
params.detail
);
origPrevent = evt.preventDefault;
evt.preventDefault = function() {
origPrevent.call(this);
try {
Object.defineProperty(this, 'defaultPrevented', {
get: function() {
return true;
}
});
} catch (e) {
this.defaultPrevented = true;
}
};
return evt;
};
return evt;
};

CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent; // expose definition to window
}
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent; // expose definition to window
}
})();

0 comments on commit ddf42a6

Please sign in to comment.