Friday, August 8, 2008

Event Programming in Javascript

Finally got to do some major event programming. A friend and I are writing some online games (and ofcourse mobile platform) which I will talk more about in another blog. Mainly I was so excited because I was able to create an event system that flows from client to server and back. Guess I have been thinking about this for a while, I wanted to use this with my Frisky project however it will have to wait. At the moment AppEngine since it is Python on the server side that you don't have to worry about all the server setup and data storage it is a no brainer. I will probably use Frisky for aspects of the streaming event system that I can't use AppEngine for but again I am getting ahead of myself.

The challenge is to have a cross platform (javascript, Objective-c or Iphone, Java or Android, Python or AppEngine). So first thing was to create a spreadsheet of all the events and some documetation of JSON that was being passed for each event. Export that to CSV file so I can generate event files in each platform. So far I have Python, Javascript, Flash and C. I haven't had time to use the C one for Iphone but hoping to start working on that next month. The next step was to write the code to dispatch events on Javascript which I could also use a special wrapper to dispatch events in Flash also. Using Javascript for Flash also saves me from writing a Flash which I don't know, however my friend Sean is coding the game in Flash so I don't have to worry about it.

Ultimately the code is very simple to write.
Registering events:
function registerCallback(typeKey, callback) {
if(EVENT_TYPES[typeKey] == undefined) {
EVENT_TYPES[typeKey] = new Array();
}
EVENT_TYPES[typeKey].push(callback);
}

And to dispatch events:
function dispatchEvent(e) {
if (EVENT_TYPES[e.type] != undefined) {
for (var i=0; i <>

That is really just about it. The rest of the code queries the server for events and then call this dispatch function. All need to code is to use this is:
function logMessage(e) {
console.log(e.data);
}
registerCallback(TYPE_MESSAGE, logMessage);

The only other aspect is the ablility to send events to the server which looks something like this:
sendEvent(TYPE_TEST, {'test':123});

That is pretty much the client side. Very simple but I think that it is amazing how powerful this is.

0 comments:

Post a Comment