[英]How to filter a local hasMany record set in Ember.js
我在過濾ul
hasMany對象的ul
時會導致dom更新的問題。 這是我要完成的工作:
當用戶單擊其中一個鏈接時,它應過濾包含相應元素的div。 這是我當前的代碼:
import Ember from 'ember';
import AuthenticatedRouteMixin from 'simple-auth/mixins/authenticated-route-mixin';
export default Ember.Route.extend(AuthenticatedRouteMixin,{
model: function (params) {
return this.store.find('recipient', params.recipient_id);
},
setupController: function (controller, model) {
this._super(controller, model);
var categories = model.get('offers').map(function(offer){
var category = Ember.Object.create();
category.name = offer.get('company_industry');
category.count = model.get('offers').filterBy('company_industry', offer.get('company_industry')).get('length');
return category;
});
controller.set('categories', categories);
}
});
這會將categories
設置為一個Ember對象,例如: {name: 'Home And Beauty', count: 1}
import Ember from 'ember';
export default Ember.Component.extend({
actions: {
filter: function(categoryName) {
return this.get('model').get('offers').filterBy("company_industry", categoryName);
}
}
});
<ul>
{{#each categories as |category|}}
<li>
<a {{action "filter" category.name}}>{{category.name}} ({{category.count}})</a>
</li>
{{/each}}
</ul>
<div class="row">
<div class="col-sm-4">
{{filterable-offers categories=categories model=model}}
</div>
<div class="col-sm-8">
{{#each model.offers as |offer|}}
<div class="offer-card">
{{offer.text}}
</div>
{{/each}}
</div>
我知道我缺少一些簡單的功能,例如在此處進行觀察,但是當我單擊鏈接以過濾掉元素時,dom中沒有任何更新。 過濾器功能確實返回了我想要的結果集,但是主接收者模板中的model.offers
調用未觀察到結果集。
您的問題是您要從操作處理程序返回過濾的結果。 動作處理程序不使用返回值(大部分情況下)。 相反,您需要將過濾后的項目放置在模板可以訪問它們的地方。 由於您的過濾器選擇器位於不同的組件中,所以這就是我要做的(如果您對此部分有任何疑問,請詢問):
在您的組件中,重新發送filter操作,使它冒泡到控制器:
actions: { filter(categoryName) { this.sendAction('filterByCategory', categoryName); } }
通過在模板中進行訂閱來確保您的控制器可以收到該動作:
{{filterable-offers categories=categories filterByCategory='filterByCategory'}}
在控制器中為filterByCategory
操作添加處理程序:
actions: { filterByCategory(categoryName) { // We'll use this in the next step this.set('filterCategory', categoryName); } }
設置一個計算屬性,該屬性將根據過濾器類別自動過濾您的項目。 我們在控制器上具有filterCategory
屬性,因此我們可以使用它:
filteredOffers: Ember.computed('model.offers.@each.company_industry', 'filterCategory', { get() { const offers = this.get('model.offers'); const filterCategory = this.get('filterCategory'); // If there's no category to filter by, return all of the offers if (filterCategory) { return offers.filterBy('company_industry', filterCategory); } else { return offers; } } })
最后,不要在模板中使用model.offers
,而要使用filteredOffers
{{#each filteredOffers as |offer|}} ... {{/each}}
這個答案可能比您想要的更深入,但是希望它會有所幫助。 您遇到的主要問題是,您需要一種方法來告訴您的控制器使用一組經過篩選的商品而不是原始商品。 這只是完成此操作的許多方法之一。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.