我有一个搜索/过滤字段,我希望能够过滤集合的任何值。我拥有的数据如下:
exports.administrators = [
{
id: 1,
firstName: "User1",
lastName: "Tester",
phone: "781-000-0000",
email: "user1.tester@email.com",
privileges: "view-only"
}, {
id: 2,
firstName: "Mickey",
lastName: "Mouse",
phone: "781-123-4567",
email: "mickey.mouse@disney.com",
privileges: "all"
}, {
id: 3,
firstName: "Snow",
lastName: "White",
phone: "781-890-1234",
email: "snow.white@disney.com",
privileges: "all"
}, {
id: 4,
firstName: "Anakin",
lastName: "Skywalker",
phone: "888-874-9084",
email: "anakin.skywalker@deathstar.com",
privileges: "view-only"
}, {
id: 5,
firstName: "Obi-one",
lastName: "Kenobi",
phone: "908-765-5432",
email: "obi.kenobi@jedi.com",
privileges: "all"
}, {
id: 6,
firstName: "Master",
lastName: "Yoda",
phone: "876-654-2134",
email: "yoda@jedi.com",
privileges: "view-only"
}, {
id: 7,
firstName: "Han",
lastName: "Solo",
phone: "781-456-3209",
email: "han.solo@gmail.com",
privileges: "all"
}, {
id: 8,
firstName: "Neo",
lastName: "TheOne",
phone: "781-000-0000",
email: "neo@matrix.com",
privileges: "all"
}];
View 将根据 keyup 事件触发一个事件:
AdministratorView.prototype.events = {
'click .sub-content th.sort, .sub-content th.sort-up, .sub-content th.sort-down': 'sortTable',
'click .light-btn': 'showAdd',
'keyup #filter-find': 'filterAdministrators'
};
我还抽象了要执行过滤的功能:
App.Utils.filterCollection = function(collection, filterValue) {
if (filterValue !== "") {
return _.filter(collection.models, function(data) {
var values;
values = _.values(data.attributes);
_.each(values, function(value) {
if (!isNaN(value)) {
value = value.toString();
}
return value.indexOf(filterValue) > 0;
});
});
}
};
我遇到的问题是:
- filterCollection 函数返回未定义
- 有没有更优雅的方式来做到这一点?
感谢您提前提供的所有帮助。
干杯,
基亚诺什
更新功能:
我用@dbaseman 的一些输入更新了函数
App.Utils.filterCollection = function(collection, filterValue) {
var filteredCollection;
if (filterValue === "") {
[];
}
return filteredCollection = collection.filter(function(data) {
return _.some(_.values(data.toJSON()), function(value) {
value = !isNaN(value) ? value.toString() : value;
return value.indexOf(filterValue) >= 0;
});
});
};
但是我仍然从函数中得到一个空的(或未定义的)值。我被踩了!!
更新 #2 找到了部分解决方案。这是 jsFiddle - http://jsfiddle.net/kianoshp/YWSSp/。它可以正确过滤,但是当我清空过滤器字段时,我希望显示原始数据集。但是现在我得到了一张空白表。致力于解决方案,但任何帮助/提示都会有所帮助。
更新 #3 最终解决方案在 jsFiddle --> http://jsfiddle.net/kianoshp/YWSSp/77/感谢@dbaseman