有人可以告诉我为什么在下面的代码中使用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
是在app中定义的,而不是在this
中定义的(设置为事件回调函数中的事件对象)。在这种情况下,要调用receivedEventil
,您可以将其作为包含对象app
的方法来调用:app.receivedEvent(...);
关于javascript - phonegap index.js文件为什么app.receivedEvent不是this.receivedEvent,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43501360/