Here is my code which suppose to handle device and network events for my phonegap application
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;
});
When I import this module I assign my own function to devicecs online event in this way
MobileDevice.Online = function() {
alert("we have updated information..");
};
but it never gets called. can anyone help me with this module? one more thing to not: this assignment is differently called after device ready event.
You aren't calling your event handlers -- you are returning references instead. Try this:
function HandleBackClick() {
return deviceHandler.OnNavigateBack();
}
function HandleOnlineState() {
return deviceHandler.Online();
}
function HandleOfflineState() {
return deviceHandler.Offline();
}
Of course, you should handle cases where you may not have a handler defined or where you have parameters being sent. I've made it a bit more generic as well, but you can ignore that if you want.
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 );
// ...