Skip to content

Commit

Permalink
Merge pull request #497 from sveltejs/window-events
Browse files Browse the repository at this point in the history
allow window events to access state
  • Loading branch information
Rich-Harris authored Apr 19, 2017
2 parents 771dacc + f1bef92 commit 386cb8b
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/generators/dom/visitors/Element/meta/Window.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,26 @@ export default function visitWindow ( generator, block, node ) {
// TODO verify that it's a valid callee (i.e. built-in or declared method)
generator.addSourcemapLocations( attribute.expression );

let usesState = false;

attribute.expression.arguments.forEach( arg => {
const { contexts } = block.contextualise( arg, null, true );
if ( contexts.length ) usesState = true;
});

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

const handlerName = block.getUniqueName( `onwindow${attribute.name}` );
const handlerBody = ( usesState ? `var root = ${block.component}.get();\n` : '' ) +
`[✂${attribute.expression.start}-${attribute.expression.end}✂];`;

block.builders.create.addBlock( deindent`
var ${handlerName} = function ( event ) {
[✂${attribute.expression.start}-${attribute.expression.end}✂];
function ${handlerName} ( event ) {
${handlerBody}
};
window.addEventListener( '${attribute.name}', ${handlerName} );
` );
Expand Down
24 changes: 24 additions & 0 deletions test/runtime/samples/window-event-context/_config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
export default {
data: {
foo: true
},

html: `true`,

skip: /^v4/.test( process.version ), // node 4 apparently does some dumb stuff
'skip-ssr': true, // there's some kind of weird bug with this test... it compiles with the wrong require.extensions hook for some bizarre reason

test ( assert, component, target, window ) {
const event = new window.Event( 'click' );

window.dispatchEvent( event );
assert.equal( component.get( 'foo' ), false );
assert.htmlEqual( target.innerHTML, `false` );

window.dispatchEvent( event );
assert.equal( component.get( 'foo' ), true );
assert.htmlEqual( target.innerHTML, `true` );

component.destroy();
}
};
3 changes: 3 additions & 0 deletions test/runtime/samples/window-event-context/main.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
<:Window on:click='set({ foo: !foo })'/>

{{foo}}

0 comments on commit 386cb8b

Please sign in to comment.