Ember.js:如何在select helper上使用观察者来过滤内容?

时间:2015-02-03 20:45:23

标签: javascript ember.js

我正在尝试使用Ember-CLI实现以下功能:

在加载项目的初始列表后,用户可以从下拉列表中选择一个城市,以仅查看他/她感兴趣的项目。就我而言,这是城市的区域。您可以从下拉列表中选择要查看的城市 只有那个城市的地区。

理想情况下,所有这些都应该在不单独调用(点击)的情况下发生。

到目前为止,我已经得到了这个,但是'filteredContent'的console.log返回了一个包含0个元素的数组。我有什么不对的提示?

区/ index.hbs:

<p>{{view "select" content=cities optionValuePath="content.id" optionLabelPath="content.name" selection=selectedCity}}</p>
{{#each item in filteredContent}}
    <p>{{item.name}} in {{item.city.name}}</p>
{{/each}}

路线:

var DistrictListRoute = Ember.Route.extend({
    model: function () {
        return this.store.find('district');
    },

    setupController: function(controller, model) {
        this._super(controller, model);
        this.store.find('city').then(function(cities) {
            controller.set('cities', cities);
        });
    }
});

export default DistrictListRoute;

控制器:

export default Ember.Controller.extend({
    filteredContent: [],
    selectedCity: null,

    selectedCityChanged: function () {
        var selectedCity = this.get('selectedCity');
        console.log(selectedCity);
        var filteredContent = this.get('model').filterBy('city', selectedCity);
        console.log(filteredContent);
    }.observes('selectedCity')
});

模型:

export default DS.Model.extend({
  city: DS.belongsTo('city', {async: true}),
  name: DS.attr('string'),
  advert: DS.hasMany('item')
});

1 个答案:

答案 0 :(得分:1)

终于明白了:

控制器:

export default Ember.ArrayController.extend({
    selectedCity: null,
    filteredContent: [],

    selectedCityChanged: function () {
        var selectedCity = this.get('selectedCity');
        var filteredContent = this.get('model').filterBy('city.id', selectedCity.id);
        this.set('filteredContent', filteredContent);
    }.observes('selectedCity')

然后,车把模板需要一些调整:

<p>{{view "select" content=cities optionValuePath="content.id" optionLabelPath="content.name" selection=selectedCity}}</p>
    {{#if filteredContent}}
        <h2>District in {{selectedCity.name}}</h2>
        {{#each district in filteredContent}}
            <p>{{district.name}}  in {{district.city.name}}</p>
        {{/each}}
        {{else}}
        <h2>Districts</h2>
        {{#each district in content}}
            <p>{{district.name}}  in {{district.city.name}}</p>
        {{/each}}
    {{/if}}