UPDATE: An updated and enhanced version of this technique is available here:
Enums in Javascript – Part 2

 

Basically, the title says it all. So, without wasting any time, let’s see an example of an enum in Javascript.

{syntaxhighlighter brush: jscript;fontsize: 100; first-line: 1; } ChangeAction = function() {
}

ChangeAction.None = 0;
ChangeAction.Insert = 1;
ChangeAction.Delete = 2;
ChangeAction.Update = 3;

ChangeAction.parse = function(str) {
var val = ChangeAction[str];
if (val != undefined) {
return (val);
} else {
for (key in ChangeAction) {
if (str == ChangeAction[key]) {
return (ChangeAction[key]);
}
}
}
throw str + ‘ cannot be parsed to ChangeAction.’;
}

ChangeAction.toString = function(val, throwIfNotFound) {
for (key in ChangeAction) {
if (val == ChangeAction[key]) {
return (key);
}
}

if (throwIfNotFound)
throw val + ‘ is not a valid ChangeAction value.’;
else
return (val);
}{/syntaxhighlighter}

I use this enum to maintain on the client-side the actions that need to be performed on data when submitted to the server. Needless to say, there is a corresponding enum on the server-side with the same keys and values.

The reason I needed to create this enum was the difference in the way enum proprties are serialized by different server-side components in .NET (e.g. the JavaScriptSerlializer, JSonDataContractSerializer, Ext.Net’s Store class etc.). Some of them used the enum’s integer value, while other’s used the descriptive string for serialization. So, I needed a transparent way to convert between the 2 representations on the client-side.

I am currently using this enum on an Ext.Net (Coolite’s) store object, which serializes the enum as its string representation, but I need the integer representation on the client-side. So, my Recordfield for the Reader looks like this:

<ext:RecordField Name="action">
        <Convert Fn="ChangeAction.parse" />
</ext:RecordField>

When the data is loaded, whatever the representation serialized, it is loaded as integer into the store.

If you are using the ExtJs client-side framework, you can easily move the parse, and toString functions from the above code in a base class, let’s say Enum. And then use the Ext.Extend method to derive classes from the base Enum class, and just define the enumeration key/values there, without needing to repeat the above methods across enums.

The attached code provides an example for the above enum functionality, and demonstrates how easy it is to convert between the 2 enum representations using the above code.