Skip to content

Commit 38ae43f

Browse files
committed
add bind:online to <:Window/> (#404)
1 parent 783cd38 commit 38ae43f

File tree

1 file changed

+32
-7
lines changed
  • src/generators/dom/visitors/Element/meta

1 file changed

+32
-7
lines changed

src/generators/dom/visitors/Element/meta/Window.js

+32-7
Original file line numberDiff line numberDiff line change
@@ -42,19 +42,22 @@ export default function visitWindow ( generator, block, node ) {
4242
}
4343

4444
if ( attribute.type === 'Binding' ) {
45-
const associatedEvent = associatedEvents[ attribute.name ];
46-
47-
if ( !associatedEvent ) {
48-
throw new Error( `Cannot bind to ${attribute.name} on <:Window>` );
49-
}
50-
5145
if ( attribute.value.type !== 'Identifier' ) {
5246
const { parts, keypath } = flattenReference( attribute.value );
5347
throw new Error( `Bindings on <:Window/> must be to top-level properties, e.g. '${parts.pop()}' rather than '${keypath}'` );
5448
}
5549

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

52+
// bind:online is a special case, we need to listen for two separate events
53+
if ( attribute.name === 'online' ) return;
54+
55+
const associatedEvent = associatedEvents[ attribute.name ];
56+
57+
if ( !associatedEvent ) {
58+
throw new Error( `Cannot bind to ${attribute.name} on <:Window>` );
59+
}
60+
5861
if ( !events[ associatedEvent ] ) events[ associatedEvent ] = [];
5962
events[ associatedEvent ].push( `${attribute.value.name}: this.${attribute.name}` );
6063

@@ -88,7 +91,7 @@ export default function visitWindow ( generator, block, node ) {
8891
}
8992

9093
block.builders.create.addBlock( deindent`
91-
var ${handlerName} = function ( event ) {
94+
function ${handlerName} ( event ) {
9295
${handlerBody}
9396
};
9497
window.addEventListener( '${event}', ${handlerName} );
@@ -124,4 +127,26 @@ export default function visitWindow ( generator, block, node ) {
124127
});
125128
` );
126129
}
130+
131+
// another special case. (I'm starting to think these are all special cases.)
132+
if ( bindings.online ) {
133+
const handlerName = block.getUniqueName( `onlinestatuschanged` );
134+
block.builders.create.addBlock( deindent`
135+
function ${handlerName} ( event ) {
136+
component.set({ ${bindings.online}: navigator.onLine });
137+
};
138+
window.addEventListener( 'online', ${handlerName} );
139+
window.addEventListener( 'offline', ${handlerName} );
140+
` );
141+
142+
// add initial value
143+
generator.builders.metaBindings.addLine(
144+
`this._state.${bindings.online} = navigator.onLine;`
145+
);
146+
147+
block.builders.destroy.addBlock( deindent`
148+
window.removeEventListener( 'online', ${handlerName} );
149+
window.removeEventListener( 'offline', ${handlerName} );
150+
` );
151+
}
127152
}

0 commit comments

Comments
 (0)