用ember选择下拉列表

Hay*_*ers 19 ember.js

我正在尝试生成一个选择输入并将所选对象传递给视图上的change事件.ember联系人示例使用a <ul>但是选择视图需要在每个视图之外,否则甚至不会触发更改.

这是js的视图:

App.SelectView = Ember.View.extend({

    change: function(e) {
        //event for select
        var content = this.get('content');
        console.log(content);   

        App.selectedWidgetController.set('content', [content]);
    },
    click: function(e) {
        //event for ul
        var content = this.get('content');
        console.log(content);   

        App.selectedWidgetController.set('content', [content]);
    }
});
Run Code Online (Sandbox Code Playgroud)

ul从示例工作:

<ul>
    {{#each App.widgetController.content}}
        {{#view App.SelectView contentBinding="this"}}
            <li>{{content.name}}</li>
        {{/view}}
    {{/each}}
</ul>
Run Code Online (Sandbox Code Playgroud)

但是,如果我直接替换html,则不会触发更改事件(这是有道理的)

<select>
    {{#each App.widgetController.content}}
        {{#view App.SelectView contentBinding="this"}}
            <option>{{content.name}}</option>
        {{/view}}
    {{/each}}
</select>
Run Code Online (Sandbox Code Playgroud)

所以我想select必须包含在视图中..在这种情况下我如何传递相关对象?...这段代码导致整个数组被传递:

{{#view App.select_view contentBinding="App.widgetController.content"}}
    <select>
    {{#each App.widgetController.content}}
        <option>{{name}}</option>
    {{/each}}
    </select>
{{/view}}
Run Code Online (Sandbox Code Playgroud)

ebr*_*ryn 36

Ember现在有一个内置的Select视图.

这是一个用法示例:

var App = Ember.Application.create();

App.Person = Ember.Object.extend({
    id: null,
    firstName: null,
    lastName: null,

    fullName: function() {
        return this.get('firstName') + " " + this.get('lastName');
    }.property('firstName', 'lastName').cacheable()
});

App.selectedPersonController = Ember.Object.create({
    person: null
});

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'})
    ]
});
Run Code Online (Sandbox Code Playgroud)

您的模板看起来像:

{{view Ember.Select
       contentBinding="App.peopleController"
       selectionBinding="App.selectedPersonController.person"
       optionLabelPath="content.fullName"
       optionValuePath="content.id"}}
Run Code Online (Sandbox Code Playgroud)

再次,这是一个jsFiddle示例:http://jsfiddle.net/ebryn/zgLCr/

  • 太棒了!希望这些例子被添加到emberjs网站,这将使学习过程减少很多痛苦 (10认同)
  • 谢谢你的小提琴.因为它与ember-latest链接,所以需要一些脚本更新.我改为使用jQuery 1.8.3和Handlebars 1.0.beta.6:http://jsfiddle.net/zgLCr/622/ (2认同)