需要解释Cordova'deviceready'事件如何运作

时间:2016-09-15 12:31:21

标签: javascript html cordova phonegap-plugins

我正在学习在Cordova PhoneGap中创建应用程序,我对使用此'deviceready'事件感到困惑。它应该是特定于Cordova API的事件,但在Hello World示例中,有关它的所有内容都在index.js文件中定义。

var app = {
    // Application Constructor
    initialize: function () {
        this.bindEvents();
    }, // Bind Event Listeners
    //
    // Bind any events that are required on startup. Common events are:
    // 'load', 'deviceready', 'offline', and 'online'.
    bindEvents: function () {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    }, // deviceready Event Handler
    //
    // The scope of 'this' is the event. In order to call the 'receivedEvent'
    // function, we must explicitly call 'app.receivedEvent(...);'
    onDeviceReady: function () {
        app.receivedEvent('deviceready');
    }, // Update DOM on a Received Event
    receivedEvent: function (id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');
        listeningElement.setAttribute('style', 'display:none;');
        receivedElement.setAttribute('style', 'display:block;');
    }
};

.html文件中有此脚本标记,但

<script src="cordova.js"></script>

所有这些设备准备代码对我来说看起来都是一个不必要的代码。 请有人向我解释为什么需要这个'deviceready'事件,以及它与Cordova API的关联程度

1 个答案:

答案 0 :(得分:1)

deviceready事件很重要。当您运行应用程序时,应用程序首先加载Cordova API'scordova plugin等。当此加载完成时,它将触发deviceready事件。它就像HTML文件的onload事件。因此,您应该在deviceready事件之后或之后执行您的工作。cordova.js使用本机平台初始化cordova API。cordova.js将在您构建应用程序时自动生成。{ {1}}是对<script src="cordova.js"></script>文件的引用。您可以在link获取cordova.js事件的详细信息。

相关问题