Displaying a Button to Remove All Completed Todos Edit Page


TodoMVC allows users to delete all completed todos at once by clicking a button. This button is visible only when there are any completed todos, displays the number of completed todos, and removes all completed todos from the application when clicked.

In this step, we'll implement that behavior. In index.html update the static <button> for clearing all completed todos:

1
2
3
4
5
6
7
{{! ... additional lines truncated for brevity ... }}
{{#if hasCompleted}}
  <button id="clear-completed" {{action "clearCompleted"}}>
    Clear completed ({{completed}})
  </button>
{{/if}}
{{! ... additional lines truncated for brevity ... }}

In js/controllers/todos_controller.js implement the matching properties and a method that will clear completed todos and persist these changes when the button is clicked:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// ... additional lines truncated for brevity ...
actions: {
  clearCompleted: function() {
    var completed = this.filterBy('isCompleted', true);
    completed.invoke('deleteRecord');
    completed.invoke('save');
  },
  // ... additional lines truncated for brevity ...
},
hasCompleted: function() {
  return this.get('completed') > 0;
}.property('completed'),

completed: function() {
  return this.filterBy('isCompleted', true).get('length');
}.property('@each.isCompleted'),
// ... additional lines truncated for brevity ...

The completed and clearCompleted methods both invoke the filterBy method, which is part of the ArrayController API and returns an instance of EmberArray which contains only the items for which the callback returns true. The clearCompleted method also invokes the invoke method which is part of the EmberArray API. invoke will execute a method on each object in the Array if the method exists on that object.

Reload your web browser to ensure that there are no errors and the behavior described above occurs.

Live Preview

Ember.js • TodoMVC

Additional Resources