Search code examples
javascriptsproutcore-2sproutcore-viewssproutcore-controllers

SproutCore Collection Sorting


I have a list of todos and I have tag property associated with them. On the views, I have a "Sort By Tag" button. When I press that button, I want the collection to be sorted by tag. Nothing is happening now. Below is the code. What's wrong?

 In todos.js I have:
 Todos.SortingView = SC.TemplateView.extend({
  sortBinding: 'Todos.todoListController.sortTodos'
});

 and in todoListController, I have:
    sortTodos: function() {
   Todos.store.find(Todos.Todo).sortProperty('tag');
  }

 and in the handlebars view I have:
{{#view Todos.SortingView id="stats"}}
  {{#view SC.Button classBinding="isActive" target="Todos.todoListController" action="sortTodos"}}
    Sort By Tag
  {{/view}}
{{/view}}

{{#collection SC.TemplateCollectionView contentBinding="Todos.todoListController" itemClassBinding="content.isDone"}}
  {{view Todos.MarkDoneView}} - Tag - {{content.tag}}
{{/collection}}

Solution

  • sortTodos: function() {
       Todos.store.find(Todos.Todo).sortProperty('tag');
    }
    

    should be:

    sortTodos: function() {
       this.set('orderBy', 'tag');
    }
    

    Now if you add items, you must use addObject and use arrangedObjects not just content


    createTodo: function(title) { 
        // var todo = Todos.Todo.create({ title: title });    
        var todoExists = this.findProperty('title', title).length > 0;
        if (!todoExist) {
            Todos.store.createRecord(Todos.Todo, { title: title }); 
            // this.pushObject(todo); 
        }
    }