phonegap index.js文件为什么app.receivedEvent不是this.receivedEvent

时间:2017-04-19 16:34:01

标签: 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);
    }
};

1 个答案:

答案 0 :(得分:1)

评论实际上解释了使用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在app中定义,而不是this(设置为事件回调函数中的事件对象)。要在这种情况下调用receivedEventil,您可以将其称为包含对象app的方法:

app.receivedEvent(...);