2017-07-19 42 views
0

我想使用meteor/cordova在iPhone上顯示當前的電池電量並作出反應。使用meteor/cordova顯示電池電量並作出反應

This是我使用的插件。

這是我想象它的工作:

export default class BatteryDetails extends Component { 

constructor(props){ 
    super(props); 

    this.currentBatteryLevel = 0; 

    function onBatteryStatus(status) { 
     this.currentBatteryLevel = status.level; 
    } 

    window.addEventListener("batterystatus", onBatteryStatus, false); 
    window.dispatchEvent(new Event('batterystatus')); 
} 

render() { 
    return (
     <div> 
      Remaining: {this.currentBatteryLevel} 
     </div> 
    ); 
} 
} 
+0

在你的'render'方法中,你試圖呈現'this.getBatteryLevel()' - 但是,它看起來像這個函數不會返回任何值。 – cathalkilleen

回答

0

我會去一些更傳統的,雖然我現在不能測試:

export default class BatteryDetails extends Component { 

    constructor(props) { 
    super(props); 

    this.state = { 
     currentBatteryLevel: 0 
    }; 

    window.addEventListener("batterystatus", (status) => this.onBatteryStatus(status), false); 
    window.dispatchEvent(new Event('batterystatus')); 
    } 

    onBatteryStatus(status) { 
    this.setState({ currentBatteryLevel: status.level }); 
    } 

    render() { 
    return ( 
     <div> 
     Remaining: { this.state.currentBatteryLevel } 
     </div> 
    ); 
    } 
} 
+0

謝謝你的答案,但不幸的是,它也不起作用。 – Phil

+0

@Phil看到我的編輯,我忘了'status'參數。無論如何,你有什麼錯誤嗎? –

+0

@ Nathan P .:我得到一個引用錯誤,指出變量'onBatteryStatus'無法解析 - 如果我沒有記錯的話。我將它的聲明移到構造函數中,不再發生錯誤,但它仍然不起作用。 – Phil

0

我想我用該PhoneGap項目中的包(而不是Meteor項目),並且我遇到了batterystatus事件的一些問題。我認爲是這樣的:

當第一次訂閱該事件時,它立即被觸發。它也可以在您下次訂閱時像這樣工作,但前提是您已取消訂閱第一個事件偵聽器。如果您犯了這個錯誤(並且忘記取消訂閱),則需要重新啓動應用程序(強制關閉它)。

但是,當您插拔充電器時,該事件總是會被觸發,所以這是測試它是否有效的便捷方式。

+0

謝謝你的信息 - 但我不明白這可以幫助我:)在我的理解問題是,事件已被觸發後,正確的價值已經消失。 – Phil

+0

啊,我現在看到你使用'dispatchEvent'。我沒有檢查源代碼,但我懷疑'cordova-plugin-battery-status'監聽這個事件併發送一個真實的'batterystatus'事件(當你發送一個事件時,它將被精確地調度,例如它不會有'level'屬性)。 –

+0

雖然在'onBatteryStatus'內記錄'status.level'確實顯示了正確的結果。我不知道我明白你想告訴我什麼:) – Phil