Simple Select control

by sohara

HTML

<script src="http://cloud.github.com/downloads/emberjs/ember.js/ember-0.9.3.js"></script>
<script type="text/x-handlebars">
  {{view App.SelectView 
         contentBinding="App.peopleController"
         selectionBinding="App.thingController.person"
         itemViewClassBinding="App.PersonOptionView"}}

  <p>Selected: {{App.selectedPersonController.person.fullName}}</p>
</script>

JavaScript

window.App = Ember.Application.create();

// Generic select views
    
App.OptionView = Ember.View.extend({
    tagName: 'option',
    valueBinding: 'content',

    template: Ember.Handlebars.compile("{{value}}")
});

App.SelectView = Ember.CollectionView.extend({
    tagName: 'select',
    itemViewClass: App.OptionView,

    selection: null,
    
    didInsertElement: function() {
        this.set('selection', this.get('content').objectAt(0));
    },
    
    change: function(event) {
        var idx = this.get('element').selectedIndex;
        this.set('selection', this.get('content').objectAt(idx));
    }
});

// App-related objects

App.Person = Ember.Object.extend({
    firstName: null,
    lastName: null,
    
    fullName: function() {
        return this.get('firstName') + " " + this.get('lastName');
    }.property('firstName', 'lastName').cacheable()
});

App.thingController = Ember.Object.create({
    nameBinding: 'App.thing.name',
    
    alertOnChange: function() {
        alert("person has changed!");
    }.observes('person')
});


App.peopleController = Ember.ArrayController.create({
    content: [
        App.Person.create({id: 1, firstName: 'Yehuda', lastName: 'Katz'}),
        App.Person.create({id: 2, firstName: 'Tom', lastName: 'Dale'}),
        App.Person.create({id: 3, firstName: 'Peter', lastName: 'Wagenet'}),
        App.Person.create({id: 4, firstName: 'Erik', lastName: 'Bryn'})
    ]
});

/* 
Subclass OptionView to specify an alternative property path
for the value of the option
*/
App.PersonOptionView = App.OptionView.extend({
    valueBinding: 'content.fullName'
});