fvisticot fvisticot - 3 months ago 9
Javascript Question

How to define an enumeration with ember-model

In my ember-model model I need to set a String attribute from an enumeration.
Is it possible with ember-model?

By Example I would like to have a Book model:

App.Book({
id: Ember.attr(),
title: Ember.attr( 'String' ),
author: Ember.attr( 'String' ),
status: App.BookStatus
});


and
App.Book.Status
as an enum with 3 possible values
"FREE", "BORROW", "LOST"
and use it:

var myBook = App.Book.create({
title:'myBook',
author:'fred',
status: App.BookStatus.FREE
})


I need the equivalent to the Java Enum feature

public enum BookStatus {
FREE, BORROW, LOST
}

class Book {
BookStatus bookStatus;
}

Book bookInstance = new Book();
bookInstance.bookStatus=BookStatus.LOST;

Answer

As stated in the docs:

In Ember.js, an Enumerable is any object that contains a number of child objects, and which allows you to work with those children using the Ember.Enumerable API.

So for example:

var players = ["Alex", "Paul", "Tom"];

players.forEach(function(item, index) {
  console.log('Player %@: %@'.fmt(index+1, item));
});

Would output:

// Player 1: Alex
// Player 2: Paul
// Player 3: Tom

To make your own custom class enumerable, you need two items:

To make your own enumerable class/object in ember you could use the Ember.Enumerable mixin and follow this two requirements:

  • You must have a length property. This property should change whenever the number of items in your enumerable object changes. If you using this with an Ember.Object subclass, you should be sure to change the length property using the built-in set() method.

  • If you must implement nextObject().

Once you have these two methods implemented, apply the Ember.Enumerable mixin to your class and you will be able to enumerate the contents of your object like any other collection.

Pseudo code:

App.MyEnumObject = Ember.Object.extend(Ember.Enumerable, {
  length: 0,
  nextObject: function() {
    //return the next object of the enumeration
  }
  //more methods and properties
});

See here for more info on enumerable in ember.

Hope it helps.

Edit

Since we are using javascript, what you are trying to do could be done in a much simpler way. For example:

App.bookStatus = {
  FREE: "FREE",
  BORROW: "BORROW",
  LOST: "LOST"
}

var myBook = App.Book.create({id: 1, title: 'myBook', author: 'fred', status: App.bookStatus.FREE})