|
1 | 1 | import { Observable } from '@nativescript/core'; |
| 2 | +import { checkBatteryLevel, listenForBatteryChanges } from '@stackblitz/nativescript-battery'; |
| 3 | + |
| 4 | +const formatMessage = (level) => `The Battery Level is: ${level}%`; |
2 | 5 |
|
3 | 6 | export class HelloWorldModel extends Observable { |
4 | | - private _counter: number; |
5 | | - private _message: string; |
| 7 | + level: number; |
| 8 | + isListening = false; |
6 | 9 |
|
7 | 10 | constructor() { |
8 | 11 | super(); |
9 | | - |
10 | | - // Initialize default values. |
11 | | - this._counter = 42; |
12 | | - this.updateMessage(); |
| 12 | + this.updateBatteryLevel(); |
13 | 13 | } |
14 | 14 |
|
15 | | - get message(): string { |
16 | | - return this._message; |
| 15 | + async updateBatteryLevel() { |
| 16 | + const value = await checkBatteryLevel(); |
| 17 | + this.updateLevel(value); |
| 18 | + alert(formatMessage(value)); |
17 | 19 | } |
18 | 20 |
|
19 | | - set message(value: string) { |
20 | | - if (this._message !== value) { |
21 | | - this._message = value; |
22 | | - this.notifyPropertyChange('message', value); |
| 21 | + async toggleListenForChanges() { |
| 22 | + this.isListening = listenForBatteryChanges((value) => { |
| 23 | + this.updateLevel(value); |
| 24 | + }); |
| 25 | + this.notifyPropertyChange('isListening', this.isListening); |
| 26 | + if (this.isListening) { |
| 27 | + // update view binding right away |
| 28 | + const value = await checkBatteryLevel(); |
| 29 | + this.updateLevel(value); |
23 | 30 | } |
24 | 31 | } |
25 | 32 |
|
26 | | - onTap() { |
27 | | - this._counter--; |
28 | | - this.updateMessage(); |
29 | | - } |
30 | | - |
31 | | - private updateMessage() { |
32 | | - if (this._counter <= 0) { |
33 | | - this.message = |
34 | | - 'Hoorraaay! You unlocked the NativeScript clicker achievement!'; |
35 | | - } else { |
36 | | - this.message = `${this._counter} taps left`; |
37 | | - } |
38 | | - |
39 | | - // log the message to the console |
40 | | - console.log(this.message); |
| 33 | + private updateLevel(value: number) { |
| 34 | + this.level = value; |
| 35 | + this.notifyPropertyChange('level', this.level); |
41 | 36 | } |
42 | 37 | } |
0 commit comments