Skip to content
Ben Leggiero edited this page Nov 26, 2019 · 3 revisions

Using an enum with this should be as easy as in most languages with native enumerated types! For For demonstrative purposes, we're using the days enum type we made in Creation.

Table of Contents

In switch statements

switch statements are really enum's bread and butter. It's what enumerated types were invented for, and this library doesn't slack on that! You can use the enumeration constants in your enum type just like you can integers in JavaScript! Here, someValue might come from a <select> dropdown or some other input that's usually harder to interpret.

Example

switch(someValue)
{
	case days.Monday:
		return "That's a hard one...";
	
	case days.Wednesday:
		return "Halfway there!!";
	
	case days.Friday:
		return "Time to party at the Party Club!";
	
	default:
		if (days.all.length <= someValue) // if someValue is in our enum
			throw "Sorry, " + days.keys[someValue] + " is not supported.";
		else
			throw "You must use a value in the 'days' enum.";
}

For <select> dropdowns

Speaking of HTML <select> element, you can use this library to help you make and interpret one quite easily!

Example

Here, we assume you've already imported micro-enum.js. We also assume you're using jQuery, just so you don't have to look through gobs of DOM-altering JavaScript.

<label id="flavor_selection_label">What flavor would you like?</label>
<output>Select an item to see it here!</output>

<script type="text/javascript">
var flavors = Enum("Vanilla", "Chocolate", "Strawberry");

var label = $("#flavor_selection_label");
label.append("<select id=\"flavor_selection_dropdown\" onchange=\"displayFlavorFrom(this)\"></select>");

var dropdown = $("#flavor_selection_dropdown");
dropdown.append("<option disabled selected>Select a flavor!</option>");

for (value in flavors.all)
    dropdown.append("<option value=\"" + value + "\">" + flavors.keys[value] + "</option>");

function displayFlavorFrom(dropdown)
{
    $("output").text(flavors.keys[dropdown.value]);
}
</script>
See it in action at http://jsfiddle.net/Supuhstar/4VhnK/
Clone this wiki locally