awesome-cordova-plugins/src/plugins/batterystatus.ts

78 lines
2.0 KiB
TypeScript
Raw Normal View History

2016-03-07 01:48:20 +08:00
import {Plugin} from './plugin';
import {Observable} from "rxjs/Observable";
/**
2016-03-11 04:14:55 +08:00
* @name Battery Status
* @description
2016-03-07 01:48:20 +08:00
* Requires Cordova plugin: cordova-plugin-batterystatus. For more info, please see the [BatteryStatus plugin docs](https://github.com/apache/cordova-plugin-battery-status).
*
* @usage
* ```js
2016-03-11 04:14:55 +08:00
* // watch change in battery status
* let subscription = BatteryStatus.onChange().subscribe(
2016-03-07 01:48:20 +08:00
* status => {
* console.log(status.level, status.isPlugged);
2016-03-07 01:48:20 +08:00
* }
* );
*
2016-03-11 04:14:55 +08:00
* // stop watch
* subscription.unsubscribe();
*
2016-03-07 01:48:20 +08:00
* ```
*/
@Plugin({
2016-03-13 08:08:47 +08:00
plugin: 'cordova-plugin-batterystatus',
repo: 'https://github.com/apache/cordova-plugin-battery-status'
2016-03-07 01:48:20 +08:00
})
export class BatteryStatus {
/**
2016-03-11 04:14:55 +08:00
* Watch the change in battery level
* @returns {Observable} Returns an observable that pushes a status object
2016-03-07 01:48:20 +08:00
*/
static onChange () : Observable<StatusObject> {
return getEventObservable("batterylevel");
}
/**
* Watch when the battery level goes low
* @returns {Observable<StatusObject>} Returns an observable that pushes a status object
*/
static onLow () : Observable<StatusObject> {
return getEventObservable("batterylow");
}
/**
* Watch when the battery level goes to critial
* @returns {Observable<StatusObject>} Returns an observable that pushes a status object
*/
static onCritical () : Observable<StatusObject> {
return getEventObservable("batterycritical");
2016-03-07 01:48:20 +08:00
}
}
2016-03-13 07:35:58 +08:00
export interface StatusObject {
/**
* The battery charge percentage
*/
level : number,
/**
* A boolean that indicates whether the device is plugged in
*/
isPlugged : boolean
}
/**
* Wrap the event with an observable
* @param event
* @returns {Observable}
*/
function getEventObservable (event : string) : Observable<StatusObject> {
return new Observable(observer => {
let callback = (status : any) => observer.next(status);
window.addEventListener(event, callback, false);
return () => window.removeEventListener(event, callback, false);
});
2016-03-11 04:14:55 +08:00
}