Skip to content

Commit

Permalink
Merge pull request #1311 from sveltejs/gh-1278
Browse files Browse the repository at this point in the history
treat component events the same as element events
  • Loading branch information
Rich-Harris authored Apr 4, 2018
2 parents 4a6807e + 029e952 commit 07a53e5
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/generators/nodes/Component.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import deindent from '../../utils/deindent';
import flattenReference from '../../utils/flattenReference';
import validCalleeObjects from '../../utils/validCalleeObjects';
import stringifyProps from '../../utils/stringifyProps';
import CodeBuilder from '../../utils/CodeBuilder';
import getTailSnippet from '../../utils/getTailSnippet';
Expand Down Expand Up @@ -479,10 +481,17 @@ function mungeEventHandler(generator: DomGenerator, node: Node, handler: Node, b

if (handler.expression) {
generator.addSourcemapLocations(handler.expression);
generator.code.prependRight(
handler.expression.start,
`${block.alias('component')}.`
);

// TODO try out repetition between this and element counterpart
const flattened = flattenReference(handler.expression.callee);
if (!validCalleeObjects.has(flattened.name)) {
// allow event.stopPropagation(), this.select() etc
// TODO verify that it's a valid callee (i.e. built-in or declared method)
generator.code.prependRight(
handler.expression.start,
`${block.alias('component')}.`
);
}

handler.expression.arguments.forEach((arg: Node) => {
const { contexts } = block.contextualise(arg, null, true);
Expand Down
1 change: 1 addition & 0 deletions test/runtime/samples/component-events-console/Widget.html
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<button on:click>click me</button>
25 changes: 25 additions & 0 deletions test/runtime/samples/component-events-console/_config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
export default {
html: '<button>click me</button>',

test(assert, component, target) {
const button = target.querySelector('button');
const messages = [];

const log = console.log;
console.log = msg => {
messages.push(msg);
};

try {
button.dispatchEvent(new window.MouseEvent('click'));
assert.deepEqual(messages, [
'clicked'
]);
} catch (err) {
console.log = log;
throw err;
}

console.log = log;
},
};
9 changes: 9 additions & 0 deletions test/runtime/samples/component-events-console/main.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<Widget on:click="console.log('clicked')"/>

<script>
import Widget from './Widget.html';

export default {
components: { Widget }
};
</script>

0 comments on commit 07a53e5

Please sign in to comment.