PDA

View Full Version : A quick way of passing js enums



dotnetCarpenter
20 Apr 2007, 3:58 AM
This is really a javascript question and not an Ext question but I figure that most people in here knows a great deal of javascript.
I really like enumerations and I've come up with a way to implement it in javascript that's almost there. First the code:

var Enum = {
GetNames: function(enumtype){
var names = [];
for (var enumName in enumtype){
names.push(enumName);
}
return names;
},
GetName: function(enumtype, enumvalue)
{
for (var enumName in enumtype){
if(enumtype[enumName] == enumvalue)
return enumName;
}
},
GetValues: function(enumtype){
var values = [];
for (var enumName in enumtype){
values.push(enumtype[enumName])
}
return values;
},
Parse: function(enumtype, enumvalue){
for (var enumName in enumtype){
if(enumtype[enumName] == enumvalue)
{
return eval(enumtype + "." + enumName);
}
}
}
}
Now to see it action you can copy/parse this:

var myEnum = { West : 1, East: 2, North : 4, South : 8 }
var br = "<br />";
document.write("var myEnum = { West : 1, East: 2, North : 4, South : 8 }");
document.write(br);
document.write('myEnum.North = ' + myEnum.North);
document.write(br);
document.write('Enum.GetNames(myEnum) = ' + Enum.GetNames(myEnum));
document.write(br);
document.write('Enum.GetValues(myEnum)) = ' + Enum.GetValues(myEnum));
document.write(br);
document.write('Enum.GetName(myEnum, 4)) = ' + Enum.GetName(myEnum, 4));
My issue is the Parse function which throws an error.

var south = {
direction:Enum.Parse(myEnum, 8)
}In Firebug I get missing ] after element list where I return the enum ([object Object].North). Does anyone know what I'm doing wrong?
Thanks - Cheers, Jon.

brian.moeskau
20 Apr 2007, 11:44 AM
Enums are great in static languages since you get strong typing and IDE code completion, but I'm not sure I get what advantage it would give you in JS? There is no typing, and because it has to be implemented as generic function calls, you wouldn't get any intellisense in an IDE. Just curious what the real-world use case would be for this?

dotnetCarpenter
30 Apr 2007, 1:11 AM
Right now I'm using Enums as lookup tables and filters. What I do is that I create an enum (BookingStatus) from a database. From that enum I create a list of radio buttons that I use to filter a grid. In my grid I have records where I only have the BookingStatus as a number but with the enum I just do this:
// render for status
function renderStatus(value, p, record){
return String.format('{0}', Enum.GetName(BookingStatus, value));
}
All of this can be done using a simple array (which is basically also what I'm doing) but I can also hard code logic like if(Booking.BookingStatus == BookingStatus.Canceled)return false; instead of if(Booking.BookingStatus == 4)return false; and having to remember that 4 equals canceled. Overall I think enums is a good way of encapsulating, well enumerations.