Skip to content

Commit

Permalink
support node methods in event handlers (#162)
Browse files Browse the repository at this point in the history
  • Loading branch information
Rich-Harris committed Dec 9, 2016
1 parent 8529e28 commit 65a99c9
Show file tree
Hide file tree
Showing 5 changed files with 23 additions and 8 deletions.
4 changes: 2 additions & 2 deletions src/generate/visitors/attributes/addElementAttributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -117,8 +117,8 @@ export default function addElementAttributes ( generator, node, local ) {
generator.addSourcemapLocations( attribute.expression );

const flattened = flattenReference( attribute.expression.callee );
if ( flattened.name !== 'event' ) {
// allow event.stopPropagation() etc
if ( flattened.name !== 'event' && flattened.name !== 'this' ) {
// allow event.stopPropagation(), this.select() etc
generator.code.prependRight( attribute.expression.start, 'component.' );
}

Expand Down
6 changes: 3 additions & 3 deletions src/utils/flattenReference.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ export default function flatten ( node ) {
node = node.object;
}

if ( node.type !== 'Identifier' ) return null;
const name = node.type === 'Identifier' ? node.name : node.type === 'ThisExpression' ? 'this' : null;

const name = node.name;
parts.unshift( name );
if ( !name ) return null;

parts.unshift( name );
return { name, keypath: parts.join( '.' ) };
}
3 changes: 0 additions & 3 deletions test/generator/event-handler-event-methods/_config.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
export default {
solo: true,
show: true,

test ( assert, component, target, window ) {
const allow = target.querySelector( '.allow-propagation' );
const stop = target.querySelector( '.stop-propagation' );
Expand Down
16 changes: 16 additions & 0 deletions test/generator/event-handler-this-methods/_config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
export default {
test ( assert, component, target, window ) {
// Click events don't focus elements in JSDOM – obviously they would
// in real browsers. More realistically, you'd use this for e.g.
// this.select(), but that's harder to test than this.focus()

const wont = target.querySelector( '.wont-focus' );
const will = target.querySelector( '.will-focus' );

wont.dispatchEvent( new window.MouseEvent( 'click' ) );
assert.equal( window.document.activeElement, window.document.body );

will.dispatchEvent( new window.MouseEvent( 'click' ) );
assert.equal( window.document.activeElement, will );
}
};
2 changes: 2 additions & 0 deletions test/generator/event-handler-this-methods/main.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
<input class='wont-focus'>
<input class='will-focus' on:click='this.focus()'>

0 comments on commit 65a99c9

Please sign in to comment.