Doing Enums in JavaScrip

Enums where added to Java in its version 1.5 and it is straightforward to use the:

public enum ChannelStates
{
  CONNECTED,
  CONNECTING,
  DISCONNECTED,
  RECONNECTING
}

Since JavaScript is becoming more and more important, at least when you are building a pretty rich ui framework, like ADF Faces,  you may run into the situation where you want the same in JavaScript. It isn’t really that hard at all. Take a look at the following JS/JSON object:

ChannelStates = { 
  CONNECTED : 0, 
  CONNECTING : 1, 
  DISCONNECTED : 2,
  RECONNECTING : 3
};

That’s all you need. However, usually, you want this object, or “enum”, to be available as a global JS object, e.g:

...
ConnectionChannel.ChannelStates = { 
  CONNECTED : 0, 
  CONNECTING : 1, 
  DISCONNECTED : 2,
  RECONNECTING : 3
};
...
ConnectionChannel.prototype.getChannelState = function()
...

This now did make the enum part of the “ConnectionChannel” class. The usage of this enum is simple too:

...
var myChannelObject = ...
if(channelObject.getChannelState() == ConnectionChannel.ChannelStates.CONNECTED)
{
  // do some work here...
}
else
...

Howdy!

Posted in adf, ajax, java, javascript, Oracle ADF Faces, web²

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: