Skip to content

Commit

Permalink
Merge pull request #462 from sveltejs/gh-404-online
Browse files Browse the repository at this point in the history
Add `bind:online` to `<:Window/>`
  • Loading branch information
Rich-Harris authored Apr 11, 2017
2 parents 229d9f0 + 38ae43f commit eaf5b6b
Showing 1 changed file with 32 additions and 7 deletions.
39 changes: 32 additions & 7 deletions src/generators/dom/visitors/Element/meta/Window.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,19 +42,22 @@ export default function visitWindow ( generator, block, node ) {
}

if ( attribute.type === 'Binding' ) {
const associatedEvent = associatedEvents[ attribute.name ];

if ( !associatedEvent ) {
throw new Error( `Cannot bind to ${attribute.name} on <:Window>` );
}

if ( attribute.value.type !== 'Identifier' ) {
const { parts, keypath } = flattenReference( attribute.value );
throw new Error( `Bindings on <:Window/> must be to top-level properties, e.g. '${parts.pop()}' rather than '${keypath}'` );
}

bindings[ attribute.name ] = attribute.value.name;

// bind:online is a special case, we need to listen for two separate events
if ( attribute.name === 'online' ) return;

const associatedEvent = associatedEvents[ attribute.name ];

if ( !associatedEvent ) {
throw new Error( `Cannot bind to ${attribute.name} on <:Window>` );
}

if ( !events[ associatedEvent ] ) events[ associatedEvent ] = [];
events[ associatedEvent ].push( `${attribute.value.name}: this.${attribute.name}` );

Expand Down Expand Up @@ -88,7 +91,7 @@ export default function visitWindow ( generator, block, node ) {
}

block.builders.create.addBlock( deindent`
var ${handlerName} = function ( event ) {
function ${handlerName} ( event ) {
${handlerBody}
};
window.addEventListener( '${event}', ${handlerName} );
Expand Down Expand Up @@ -124,4 +127,26 @@ export default function visitWindow ( generator, block, node ) {
});
` );
}

// another special case. (I'm starting to think these are all special cases.)
if ( bindings.online ) {
const handlerName = block.getUniqueName( `onlinestatuschanged` );
block.builders.create.addBlock( deindent`
function ${handlerName} ( event ) {
component.set({ ${bindings.online}: navigator.onLine });
};
window.addEventListener( 'online', ${handlerName} );
window.addEventListener( 'offline', ${handlerName} );
` );

// add initial value
generator.builders.metaBindings.addLine(
`this._state.${bindings.online} = navigator.onLine;`
);

block.builders.destroy.addBlock( deindent`
window.removeEventListener( 'online', ${handlerName} );
window.removeEventListener( 'offline', ${handlerName} );
` );
}
}

0 comments on commit eaf5b6b

Please sign in to comment.