javascript - PhoneGap Index.js 文件为什么 app.receivedEvent 不是 this.receivedEvent

标签 javascript phonegap

有人可以告诉我为什么在下面的代码中使用 app.receivedEvent('deviceready') 而不是 this.receivedEvent('deviceready') 吗?

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;');

        console.log('Received Event: ' + id);
    }
};

最佳答案

这些注释实际上解释了使用 app 而不是 this 的原因:

// The scope of 'this' is the event. In order to call the 'receivedEvent' 
// function, we must explicitly call 'app.receivedEvent(...);'

基本上,事件处理程序将使用其自己的 this 上下文调用事件回调(其中 this 将是事件对象)。

方法 receivedEvent 是在应用程序中定义的,而不是 this (设置为事件回调函数内的事件对象)。在这种情况下,要调用 receivedEventil,您可以将其作为包含对象 app 的方法来调用:

app.receivedEvent(...);

关于javascript - PhoneGap Index.js 文件为什么 app.receivedEvent 不是 this.receivedEvent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43501360/

相关文章:

ios - cordova-plugin-facebook4 - iOS 构建失败,错误代码为 65,可能是因为缺少 native 依赖项

javascript - 在模板页面中显示ajax数据 - Framework7

javascript - 从JavaScript向C++发送数据,超过127的字节值被替换为 "replacement character"

javascript - 是否可以在 Angular 容器微前端中将 Angular JS 作为微前端运行?

javascript - 调用angularjs的函数而不是jquery

android - Meteor 应用程序,如果我们添加一个新的 cordova 插件,我们是否必须重新提交该应用程序或由 meter hotcode push 处理?

cordova - Phonegap Build IOS13 - 13.2 键盘听写/语音转文本不再工作

javascript - Android 应用程序上的 Cordova 音量按钮功能

javascript - 当提交 promise 的 then() 时,Vuex3 突变不起作用

javascript - GSAP 时间线动画