javascript - 如何使用 Ember.js 显示(在 View 中)列表子集?

标签 javascript ember.js

我有一个对象列表,通过 Ajax 从 API 获取。它类似于这样:

App.Card = Ember.Object.extend({
  name: "",
  color: ""
});

App.cardsController = Ember.ArrayController.create({
  content: [],

  createCard: function(data) {
    this.pushObject(App.Card.create(data));
  },

  loadCards: function() {
    // Fetch API and use createCard
  }
});

当我使用 {{#each App.cardsController}} 时,我列出了 Controller 中的所有卡片。

但我想按颜色过滤它们。如何过滤列表(在 Controller 的内容中)并显示它们?

我试过这种方法:

App.cardsController 中添加这段代码:

  filterCardsByColor: function() {
    array = this.get('content').filter(function(item, index) {
      return item.get('color') == 'red';
    });
    return array;
  }.property('content.@each')

并将 {{#each App.cardsController.filterCardsByColor}} 添加到我的 View 中。

但我的 Chrome 控制台出现以下错误:

Uncaught TypeError: Object [object Object] has no method 'addArrayObserver' ember.min.js:18

我做错了什么?或者我该怎么办?我应该将该逻辑移至 View 吗?如何?我什至尝试将 array 包装在 Ember.Array.create(array) 中,但这并没有解决我的问题。

奖励:是否可以通过某种方式向 filterCardsByColor 发送参数,这样我就可以请求'red' 卡或'yellow' 卡,等等?

最佳答案

最好的方法是存储一个数组,该数组将保存要过滤掉的颜色(或者过滤掉,如果你愿意的话),并在每次它的 length 时更新计算属性通过指定 .property('colours.length'); 进行更改:

filteredContent: function() {
    // Triggered every time a colour is added/removed.
    var colours = this.get('colours');
    return this.get('content').filter(function(model) {
        // Determine whether the current model's colour is in the array of those filtered.
        return Boolean(jQuery.inArray(model.get('colour'), colours) == -1);
    });
}.property('colours.length')

然后我们只需要一种方法让我们的 View 能够传入颜色以添加到该数组。我们可以使用一个名为 applyFilters 的不同函数来执行此操作,该函数将接受一个参数——我们希望排除的颜色。您可以像这样在 {{action}} 中传递这种颜色:<a {{action "applyFilter" "red"}}>

applyFilter: function(colour) {
    var colours = this.get('colours');
    if (!colour) {
        // Clear all of the colours if we're clearing the filters.
        colours.clear();
        return;
    }

    // Otherwise we can push the new colour into the array, which will trigger
    // an update of the filteredContent computed property.
    colours.pushObject(colour);
}

完全可用的 JSFiddle 供您使用:http://jsfiddle.net/9XmqL/

关于javascript - 如何使用 Ember.js 显示(在 View 中)列表子集?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14805099/

相关文章:

javascript - 控制 ember promise 解析的顺序?

ember.js - 如何将供应商JavaScript添加到ember-cli 2.2

javascript - 如何转义 Handlebars 中的字符

javascript - 没有 bower 的 Ember-Cli 导入 js

javascript - 使用自定义元素时 Firefox 中的递归过多

javascript - 如何对 Firefox 57 WebExtensions 进行单元测试?

html - Ember.js 浏览器支持吗?

javascript - 不同 iOS 设备(Cordova/phonegap)的 safari 中的不同主体

javascript - 自定义函数的内联输入

javascript - jQuery 将对象添加到动态父对象