gpt4 book ai didi

javascript - EmberJS 如何构建动态过滤

转载 作者:行者123 更新时间:2023-11-28 05:33:16 24 4
gpt4 key购买 nike

我有一个可以排序、过滤和查询的项目列表。

对它们进行排序非常简单:

var ToDoList = Ember.Object.extend({
// using standard ascending sort
todosSorting: ['name:desc'],
sortedTodos: Ember.computed.sort('todos', 'todosSorting')
});

然后您可以轻松地将 todosSorting 的值更改为例如['name:asc'] 或每个待办事项的名称。 EmberJS Magic 会对一切进行排序。您甚至可以将 todosSorting 更改为 todos 的另一个属性,它就可以了。

过滤功能似乎不太强大。您可以给出一个函数或一个键加值。它没有那么强大。您可以更改每个待办事项的过滤属性,列表将被过滤。但是如何更改过滤器的值或键呢?

是否有办法实现与 .sort() 相同级别的灵 active

例如:

var ToDoList = Ember.Object.extend({
todosFilteringKey: 'priority',
todosFilteringValue: 1,
filteredTodos: Ember.computed.filter('todos', 'todosFilteringKey', 'todosFilteringValue')
});

目前我是这样实现的:

var ToDoList = Ember.Object.extend({
currentFilter: 'all',
filterBy: Ember.computed('currentFilter', function() {
return this.filters[this.get('currentFilter')];
}),

filters: {
all: function(item) {
return true;
},

priority1: function(item) {
return item.get('priority') === 1;
},

priority2: function(item) {
return item.get('priority') === 2;
},
}

filteredTodos: Ember.computed('todos', 'filterBy', 'todos.@each.priority', function () {
return this.filter();
}),

filter: function() {
return this.get('todos').filter(function(todo) {
return this.get('filterBy')(todo);
}.bind(this));
},
});

如果您有多种过滤可能性,则这不能很好地扩展

最佳答案

您可以采用多种不同的方式来编写此内容。与 sort 不同,filterfilterBy API 不提供按给定键和值动态筛选的方法。但是您可以使用如下代码自行实现该 API:

var filterByKeyAndValue = function filterByKeyAndValue(items, key, value) {
return items.filter(function (item) {
return Ember.get(item, key) === value;
});
};

var ToDoList = Ember.Object.extend({

currentPriority: null,

filteredTodos: Ember.computed('todos', 'todos.@each.priority', 'currentPriority', function() {
if (!this.get('currentPriority')) {
// slice ensures we consistently return a new Array.
return this.get('todos').slice();
}

return filterByKeyAndValue(this.get('todos'), 'priority', this.get('currentPriority'));
}),

});

这有帮助吗?

我已经在这里对 key 进行了硬编码('priority'),但是当然,您也可以将其分解到 Ember.Object 中。

关于javascript - EmberJS 如何构建动态过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39538352/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com