Filter element EmberJS elements as user types

I am very new to Ember and trying to write a simple search / filter for an array of elements in EmberJS, but it seems more complicated than it seems. I found a similar one here , but I cannot bind the search input to a function. My example is the unprincipled Todo app, which is located on the EmberJS website.

<script type="text/x-handlebars" data-template-name="todos"> {{input type="text" id="search-todo" placeholder="Search Todo List..." value=searchTerm}} ..... </script> 

In my App.TodosController I have

 searchResult: function(){ var searchTerm = this.get('searchTerm'); if(!searchTerm.trim()){return;} var regExp = new RegExp(searchTerm); return this.get('content').filter(function(item){ return regExp.test(item.get('title')); }); }.property('searchTerm','@each.title') 

but when I print, nothing happens. I tried adding searchResult to the actions hash of the control, and I see that the function is called when I add action= searchResult to the script tag, but I am not doing anything. Basically, I just need simple filtering of a list, such as AngularJS , and I want it to be not only above the title , but all the content, and I do not need it to be a separate route if it should be in a separate route, I still don’t know how to do this.

http://jsbin.com/AViZATE/20/edit

Thanks for your help.

+4
source share
2 answers

I managed to solve this problem by adding the observes keyword.

Here is the link to the solution http://jsbin.com/AViZATE/37

 searchResult: function(){ var searchTerm = this.get('searchTerm'); var regExp = new RegExp(searchTerm,'i'); this.get('model').set('content',this.store.filter('todo',function(item){ return regExp.test(item.get('title')); })); }.observes('searchTerm') 

And in html I have

 {{input type="text" id="search-todo" placeholder="Search Todo List..." value=searchTerm}} 
+4
source

The "Ember way" for this is to create a custom view that listens for the keyUp event (or any other event ) and sends a search request to the controller function:

 Todos.SearchTodoView = Ember.TextField.extend({ keyUp: function(event){ this.get('controller').send('searchResult', this.value); } }); 

For some reason, I can't get this to work on the udpated fiddle when I try to access the controller from the view, which it returns the view itself. But I know that this works as I use it in my application.

0
source

Source: https://habr.com/ru/post/1502262/


All Articles