这是index.js文件的代码快照,默认情况下会在新的phonegap项目中创建。
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);
}
};
第11行,
document.addEventListener('deviceready', this.onDeviceReady, false);
我认为this.onDeviceReady
是一个函数调用,为什么这里没有()
this.onDeviceReady()
?
答案 0 :(得分:3)
this.onDeviceReady
是函数引用。在函数上使用()
时,它会立即被调用。
当使用函数引用时,函数被传递给另一个函数,当某个事件发生时,函数被调用。
这与
相同function somefun(callback) {
// When something ASYNCHRONOUS process completes, call the callback function
callback();
}
var myFun = function() {
console.log('in myFun');
};
function somefun(myFun);
答案 1 :(得分:1)
如果我们在将函数作为引用传递时使用()和this.onDeviceReady
,则会立即调用onDeviceReady()方法。