javascript - Optimizing emberjs filter search -
i have simple search input filters through api response represented in html table. filtering works reasons feel ugly way go it. i', wondering better way go it.
here controller:
export default ember.arraycontroller.extend({ searchkeyword: null, searchresults: function(){ var searchtext = this.get('searchtext'); if( ! searchtext) return; //youve got companies dont go 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 route:
export default ember.route.extend(authenticatedroutemixin, { model: function(){ var adapter = addressbookhomeadapter.create(); var companies = adapter.findall(); return companies; } });
here adapter (i'm 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 ugly (in 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 way me directly filter model route? don't need necessary if statement? should make component correct?
you change controller return records when no search term entered, , filter
when searchkeyword
has text. in template can remove if
statement , 2nd each
. similar 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}}
Comments
Post a Comment