这是我的代码,它假设处理我的phonegap应用程序的设备和网络事件
define(['jquery', 'knockout'], function ($, ko) {
var deviceHandler = {
Online: null,
Offline: null,
OnNavigateBack: null
};
function HandleBackClick() {
return deviceHandler.OnNavigateBack;
}
function HandleOnlineState() {
return deviceHandler.Online;
}
function HandleOfflineState() {
return deviceHandler.Offline;
}
document.addEventListener('online', HandleOnlineState, false);
document.addEventListener('offline', HandleOfflineState, false);
document.addEventListener('backbutton', HandleBackClick, false);
return deviceHandler;
});
当我导入此模块时,我以这种方式将自己的功能分配给devicecs在线事件
MobileDevice.Online = function() {
alert("we have updated information..");
};
但它永远不会被调用。任何人都可以帮我这个模块吗?还有一件事要做:在设备就绪事件之后,这个赋值会被不同地调用。
答案 0 :(得分:1)
您没有调用事件处理程序 - 而是返回引用。试试这个:
function HandleBackClick() {
return deviceHandler.OnNavigateBack();
}
function HandleOnlineState() {
return deviceHandler.Online();
}
function HandleOfflineState() {
return deviceHandler.Offline();
}
当然,您应该处理您可能没有定义处理程序或者您正在发送参数的情况。我已经把它变得更通用了,但如果你愿意,你可以忽略它。
function _callEventHandler ( eventHandler ) {
var handler;
var args = Array.prototype.slice.call(arguments, 1); // skip the first parameter
if (typeof deviceHandler[eventHandler] !== "undefined") {
handler = deviceHandler[eventHandler];
if (typeof handler === "function") {
handler.apply (this, args);
} else {
console.log ( "WARNING: event handler isn't a function", eventHandler );
}
} else {
console.log ( "WARNING: event handler isn't defined", eventHandler );
}
}
// a bit more generic so you can add events easily without duplicating a lot of code
// down the line. Of course, it might be better to simply register for the event
// when the handler is assigned -- you could use properties for that
[ [ "online", "Online" ],
[ "offline", "Offline" ],
[ "backbutton", "OnNavigateBack" ]
].forEach ( function ( evt )
{
document.addEventListener ( evt[0], _callEventHandler.bind(this, evt[1]), false );
}
);
// if you don't want to be that generic you can still:
// document.addEventListener ( "online", _callEventHandler.bind(this, "Online"), false );
// ...