Skip to content

Commit

Permalink
feat: assert against preventDefault for passive events
Browse files Browse the repository at this point in the history
  • Loading branch information
buschtoens committed Apr 15, 2019
1 parent 735d639 commit 2a1110f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
23 changes: 20 additions & 3 deletions addon/utils/event-listener.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
/* eslint no-param-reassign: "off" */

import { assert } from '@ember/debug';
import { DEBUG } from '@glimmer/env';

/**
* Internet Explorer 11 does not support `once` and also does not support
* passing `eventOptions`. In some situations it then throws a weird script
Expand Down Expand Up @@ -72,19 +77,31 @@ export function addEventListenerOnce(
* @param {object} [eventOptions]
*/
export function addEventListener(element, eventName, callback, eventOptions) {
const _callback =
DEBUG && eventOptions && eventOptions.passive
? function(event) {
event.preventDefault = () => {
assert(
`ember-on-modifier: You marked this listener as 'passive', meaning that you must not call 'event.preventDefault()'.`
);
};
return callback.call(this, event);
}
: callback;

if (SUPPORTS_EVENT_OPTIONS) {
element.addEventListener(eventName, callback, eventOptions);
element.addEventListener(eventName, _callback, eventOptions);
} else if (eventOptions && eventOptions.once) {
addEventListenerOnce(
element,
eventName,
callback,
_callback,
Boolean(eventOptions.capture)
);
} else {
element.addEventListener(
eventName,
callback,
_callback,
Boolean(eventOptions && eventOptions.capture)
);
}
Expand Down
17 changes: 17 additions & 0 deletions tests/integration/modifiers/on-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,23 @@ module('Integration | Modifier | on', function(hooks) {
);
});

test('it raises an assertion when calling `event.preventDefault()` on a `passive` event', async function(assert) {
assert.expect(1);

this.handler = event => {
assert.expectAssertion(
() => event.preventDefault(),
`ember-on-modifier: You marked this listener as 'passive', meaning that you must not call 'event.preventDefault()'.`
);
};

await render(
hbs`<button {{on "click" this.handler passive=true}}></button>`
);

await click('button');
});

(gte('3.0.0') // I have no clue how to catch the error in Ember 2.13
? test
: skip)('it raises an assertion if an invalid event option is passed in', async function(assert) {
Expand Down

0 comments on commit 2a1110f

Please sign in to comment.