I am looking for a solution to bind an object attribute that contains an array of string (representing an enum on the server) to a list of checkboxes. The binding should be two-way.
On the server, we have some enum defintion, e.g., Role with the values “ADMIN”, “GUEST”, “USER”. A user object may have several of thus roles, thus the user object in Ember is of the form
App.User = Ember.Object.create({
roles: ["USER", "ADMIN"]
});
In the user administration, there should be a group of checkboxes. One checkbox per role. So, it is possible to select none, all, or several.
I know that there is the Ember.Checkbox view that can be used for this. What I am looking for would be a easy and generic view to handle any kind of enums as mentioned above.
Thus, the questions are:
- has somebody a nice solution for this?
- does anybody know a opensource project providing such extensions to ember?
Thanks in advance. // ph
A generic way to handle a two way binding between an Ember object and Checkboxes can be implemented using plain Ember.js without the need of any plugins if you are willing to sync the enums on the server and the client manually (using AJAX or WebSockets). Note that Ember can update the list of options with Checkbox automatically after a sync.
So henceforth, I will assume that you have am enum with roles as an Ember Array:
Then we will show the options available to the user in a CollectionView like this (the template is given below).
The template for each option is:
Note that the use of
<label>tag makes sure that the Checkbox’sclickevent is fired on clicking anywhere on the tag.Finally the
App.RoleCheckboxis an extension of theEmber.Checkboxclass which handles thecheckedproperty andclickevent to toggle the role:An working example of this is: http://jsfiddle.net/BLQBf/ (Look at the console to see the log messages)
Note that this is not completely Ember-esque, since the View is doing part of the job meant for the
controller. Ideally, theclickevent would call a function on theRoleCheckboxControllerwhich would make changes to theUserobject.