@@ -42,19 +42,22 @@ export default function visitWindow ( generator, block, node ) {
42
42
}
43
43
44
44
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
-
51
45
if ( attribute . value . type !== 'Identifier' ) {
52
46
const { parts, keypath } = flattenReference ( attribute . value ) ;
53
47
throw new Error ( `Bindings on <:Window/> must be to top-level properties, e.g. '${ parts . pop ( ) } ' rather than '${ keypath } '` ) ;
54
48
}
55
49
56
50
bindings [ attribute . name ] = attribute . value . name ;
57
51
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
+
58
61
if ( ! events [ associatedEvent ] ) events [ associatedEvent ] = [ ] ;
59
62
events [ associatedEvent ] . push ( `${ attribute . value . name } : this.${ attribute . name } ` ) ;
60
63
@@ -88,7 +91,7 @@ export default function visitWindow ( generator, block, node ) {
88
91
}
89
92
90
93
block . builders . create . addBlock ( deindent `
91
- var ${ handlerName } = function ( event ) {
94
+ function ${ handlerName } ( event ) {
92
95
${ handlerBody }
93
96
};
94
97
window.addEventListener( '${ event } ', ${ handlerName } );
@@ -124,4 +127,26 @@ export default function visitWindow ( generator, block, node ) {
124
127
});
125
128
` ) ;
126
129
}
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
+ }
127
152
}
0 commit comments