How to bind value form input select to attribute in controller

后端 未结 4 804
执笔经年
执笔经年 2020-12-16 05:10

I try to bind value from input select to attribute \"selectedValue\" in controller.

This is app.js

Food = Ember.Application.create();

Food.appsContr         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-16 05:31

    Jumping off from the solution for @pangrantz, this Fiddle example (http://jsfiddle.net/bsyjr/) illustrates some improvements: The Handlebars code is cleaner through the use of tagName. When tagName is set to "select", the child views automatically become "option" elements. See the Ember.CollectionView.CONTAINER_MAP in https://github.com/emberjs/ember.js/blob/master/packages/ember-views/lib/views/collection_view.js to understand why. On the Javascript side, by specifying an itemViewClass, we can add the value attribute to the option element.

    
    
    Food = Ember.Application.create();
    
    Food.SelectView = Ember.CollectionView.extend({
        value: null,
        itemViewClass: SC.View.extend({
            attributeBindings:['value'],
            valueBinding: 'content.value'
        }),
    
        valueChanged: function(){
            this.$().val( this.get('value') );
        }.observes('value'),
    
        didInsertElement: function(){
            var self = this;
            this.$().change(function(){
                var val = $('select option:selected').val();
                self.set('value', val);
            });
        }
    });
    
    Food.appsController = Ember.Object.create({
      selectedValue: ""
    });
    
    Food.Todo = Ember.Object.extend({
      title: null,
      value: null
    });
    
    Food.foodController = Ember.ArrayProxy.create({
      content: []
    });
    
    Food.foodController.pushObject(Food.Todo.create({title:"a", value:"1"}));
    Food.foodController.pushObject(Food.Todo.create({title:"b", value:"2"}));
    Food.foodController.pushObject(Food.Todo.create({title:"c", value:"3"}));
    

    There is still room for improvement in the event handling, which is not using Ember's event framework, and it would make a lot of sense to use a custom written SelectView that doesn't leverage Handlebars, since IMO, it is dubious how much value Handlebars adds in this case.

提交回复
热议问题