Emberjs filter search optimization

I have a simple search input that filters through the api response which is presented in the html table. The filtering works really well, but for some reason I feel like it was a very ugly way to go. So I am wondering what would be the best way.

here is my controller:

export default Ember.ArrayController.extend({
    searchKeyword: null,

    searchResults: function(){
        var searchText = this.get('searchText');

        if( ! searchText) return;

        //YOUVE ALREADY GOT THE COMPANIES DONT GO BACK TO THE SERVICE
        var companies =  this.get('model');

        var regex = new RegExp(searchText, 'i');

        return companies.filter(function(company){
            return company.name.match(regex);
        });
    }.property('searchText', 'model')
});

      

here is my route:

export default Ember.Route.extend(AuthenticatedRouteMixin, {
    model: function(){
        var adapter = AddressBookHomeAdapter.create();
        var companies =  adapter.findAll();
        return companies;
    }
});

      

here is my adapter (I am not using Ember-Data):

export default Ember.Object.extend({
    findAll: function(){
        return ajax('http://localhost:8000/api/v1/companies')
            .then(function(response){
                return response.data;
            });
    }
});

      

here is a very ugly (in my opinion) html {{#each}}

:

    {{#if searchResults}}
        {{#each searchResult in searchResults}}
            <tr>
                <td>{{searchResult.name}}</td>
            </tr>
        {{/each}}
    {{else}}
        {{#each m in model}}
            <tr>
                <td>{{m.name}}</td>
            </tr>
        {{/each}}
    {{/if}}

      

Is there a way to directly filter the route of the model? So I don't need an if statement? Also, probably I should make this component correct?

+3


source to share


1 answer


You can change your controller so that you always return all records when no search term has been entered, and only filter

when it searchKeyword

has text. Then in the template you can remove the operator if

and the second each

. Something similar to the following:

JS:

export default Ember.ArrayController.extend({

    searchKeyword: null,

    searchResults: function() {

        var searchKeyword = this.get('searchKeyword'),
            companies     = this.get('model');

        if (Ember.isEmpty(searchKeyword)) return companies;

        var regex = new RegExp(searchKeyword, 'i');

        return companies.filter(function(company){
            return company.name.match(regex);
        });

    }.property('searchKeyword', 'model')
});

      



HBS:

{{#each searchResult in searchResults}}
<tr>
    <td>{{searchResult.name}}</td>
</tr>
{{/each}}

      

+4


source







All Articles