[英]Ember.js: How to use an observer on select helper to filter content?
我正在嘗試通過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')
});
終於弄清楚了:
控制器:
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}}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.