For simple enum's in Ember, just using a simple JavaScript object, as shown at the bottom of @intuitivepixel's answer would suffice, but you can get a bit more functional, Ember-style enums with ember-computed-enum.
It allows getting and setting by more JavaScript-style-friendly names:
myBook.get('status'); // -> 'free'
myBook.set('status', 'lost');
myBook.get('status'); // -> 'lost'
myBook.save(); // -> saves `status: "LOST"` to the server
but also adds enumNameIsValue
properties that are particularly useful in templates:
myBook.get('statusIsLost'); // -> true
myBook.get('statusIsFree'); // -> false
Install with ember install ember-computed-enum
, then usage is pretty simple
Assuming your model looks something like:
// app/models/book.js
import DS from 'ember-data';
export default DS.Model.extend({
title: DS.attr('string'),
author: DS.attr('string'),
statusCode: DS.attr('string')
});
Where statusCode
is returned from the server as one of "FREE"
, "BORROW"
, or "LOST"
You would add a mixin-style Ember enum like this:
// app/models/book.js
import DS from 'ember-data';
import { computedEnumMixin } from 'ember-computed-enum';
BOOK_STATUS_ENUM = {
free: "FREE",
borrow: "BORROW",
lost: "LOST"
};
export default DS.Model.extend(
computedEnumMixin('status', 'statusCode', BOOK_STATUS_ENUM),
{
title: DS.attr('string'),
author: DS.attr('string'),
statusCode: DS.attr('string')
});
If you're not able to change the name of the status
field to statusCode
in the API, and still want to use the name status
to access the value within your code, you can remap the model field name using a serializer:
// app/serializers/book.js
import DS from 'ember-data';
export default DS.JSONAPISerializer.extend({
attrs: {
statusCode: 'status' // map the API's "status" field to the "statusCode" field on the model
}
});
Note: I've made the examples to reflect current (Feb 2017) ember-cli conventions, rather than the older globals style of the question