Emberjs:Paginating Fixture Data

时间:2014-04-23 03:09:05

标签: javascript ember.js

我正在构建一个搜索框,用于过滤记录并查找searchBy类别中具有指定编号的任何实体:

MyApp.SearchController = Em.ObjectController.extend({

searchTerm: "",
searchBy: "id",
searchFor: "customer",
results: function(){
    if(this.get('searchTerm') !== ""){
        var searchObj = {};
        searchObj[this.get('searchBy')] = this.get('searchTerm');
        var that = this;
        return this.store.all(this.get('searchFor'))
        .filter(function(entity){
            return ('' + entity.get(that.get('searchBy'))).indexOf(that.get('searchTerm')) != -1;
        });
    } else return [];
}.property('searchTerm', 'searchBy', 'searchFor'),
...
});

然而,只要我点击“1”就会出现大量CPU峰值,因为它会过滤掉每个记录并检查每个ID。

有没有办法限制过滤器以便它只返回前10个匹配项?

1 个答案:

答案 0 :(得分:1)

你可以做一些事情,首先应该在这里使用限制/去抖,http://emberjs.com/api/classes/Ember.run.html#method_debounce。这是一个去抖动,开始输入的例子,它会在你停止输入至少500毫秒之后才开始搜索。 http://emberjs.jsbin.com/covovaye/2/edit

您无需致电all,然后filter,只需致电filter并向其发送一个功能作为过滤器。此外,您可以通过获取searchBy和searchTerm来保存相当多的调用,然后反复使用这些变量,而不是调用反复搜索。

results: function(){
    if(this.get('searchTerm') !== ""){
        var searchObj = {},
            searchBy = this.get('searchBy'),
            searchTerm = this.get('searchTerm');
        searchObj[searchBy] = searchTerm;
        var that = this;
        return this.store.filter(this.get('searchFor'), function(entity){
            return ('' + entity.get(searchBy)).indexOf(searchTerm) != -1;
        });
    } else return [];
}.property('searchTerm', 'searchBy', 'searchFor')

如果您真的想获得前10个,可以使用slice

results: function(){
    if(this.get('searchTerm') !== ""){
        var searchObj = {},
            searchBy = this.get('searchBy'),
            searchTerm = this.get('searchTerm');
        searchObj[searchBy] = searchTerm;
        var that = this;
        return this.store.all(this.get('searchFor'))
                                  .toArray()
                                  .slice(0,10)
                                  .filter(function(entity){
            return ('' + entity.get(searchBy)).indexOf(searchTerm) != -1;
        });
    } else return [];
}.property('searchTerm', 'searchBy', 'searchFor')