Skip to content

Commit

Permalink
Improve preventDefault fix for rails-ujs
Browse files Browse the repository at this point in the history
Improves 049a337:

* Attempt native `preventDefault()` before stepping in
* Fix that calling `preventDefault()` more than once would throw an error
* Fix that non-cancelable events could be canceled
  • Loading branch information
javan committed Jan 1, 2018
1 parent 5e4b704 commit 41e3bbd
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions actionview/app/assets/javascripts/rails-ujs/utils/event.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,22 @@
CustomEvent = window.CustomEvent

if typeof CustomEvent isnt 'function'
CustomEvent = (event, params) ->
window.CustomEvent = (event, params) ->
evt = document.createEvent('CustomEvent')
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail)
# IE does not set `defaultPrevented` when `preventDefault()` is called on CustomEvents
# http://stackoverflow.com/questions/23349191/event-preventdefault-is-not-working-in-ie-11-for-custom-events
evt.preventDefault = ->
Object.defineProperty this, 'defaultPrevented', get: ->
true
evt

CustomEvent.prototype = window.Event.prototype

# Fix setting `defaultPrevented` when `preventDefault()` is called
# http://stackoverflow.com/questions/23349191/event-preventdefault-is-not-working-in-ie-11-for-custom-events
{ preventDefault } = CustomEvent.prototype
CustomEvent.prototype.preventDefault = ->
result = preventDefault.call(this)
if @cancelable and not @defaultPrevented
Object.defineProperty(this, 'defaultPrevented', get: -> true)
result

# Triggers a custom event on an element and returns false if the event result is false
# obj::
# a native DOM element
Expand Down

0 comments on commit 41e3bbd

Please sign in to comment.