Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>So the end result was that attempting to turn everything into a kb.collectionObservable was the wrong approach. The better solution was to create a secondary ko.computed result, which then implemented all the filtering and sorting that I needed. </p> <pre><code>var model = new Backbone.Model({ items: new Backbone.Collection([ new Backbone.Model({ ID: 1 }), new Backbone.Model({ ID: 2 }) ]) }); var vm = new kb.ViewModel(model); vm.Sort() = ko.observable("asc"); vm.SortBy() = ko.observable("ID"); vm.Page() = ko.observable(1); vm.Filters() = ko.observableArray([]); vm.PageSize() = ko.observable(20); vm.Filtered = ko.computed(function () { var items = vm.items; // Sorting items = items.sort(function (first, second) { var sortby = vm.SortBy(); if (first[sortby]() == second[sortby]()) return 0; if (vm.Sort() == "asc") { return first[sortby]() &lt; second[sortby]() ? -1 : 1; } if (vm.Sort() == "desc") { return first[sortby]() &gt; second[sortby]() ? -1 : 1; } return 0; }); // Filter items = ko.utils.arrayFilter(items, function (vm) { var filter = true; $.each(vm.Filters(), function (i, filtr) { var json = JSON.stringify(vm.model().attributes).toLowerCase(); if (json.indexOf(filtr.toLowerCase()) &lt; 0) filter = false; }); return filter; }); // Paging var startIndex = (vm.Page() - 1) * vm.PageSize(); var endIndex = vm.Page() * vm.PageSize(); items = items.slice(startIndex, endIndex); return items; }); </code></pre> <p>Additional, you may also need to set sorting on the model itself, so that new items get added in the right order:</p> <pre><code>var setModelComparator = function () { vm.model().get("items").comparator = function (a, b) { var by = vm.Sort() == "asc" ? 1 : -1; var field = vm.SortBy(); if (a.get(field) == 0) return -1 * by; if (b.get(field) == 0) return 1 * by; if (a.get(field) &lt; b.get(field)) return 1 * by; if (a.get(field) &gt; b.get(field)) return -1 * by; return 0; }; }; </code></pre> <p>Perhaps this is just a case of Knockback being a work in progress and not updating the API docs, who knows.</p> <p>Thanks also to bvoleti who pointed out the use of <a href="http://kmalakoff.github.io/knockback/tutorial_nested_models.html" rel="nofollow">Nested Models</a>, a very important part of knockbacks arsenal, particularly when teamed up with <a href="http://backbonerelational.org/" rel="nofollow">Backbone.Relational</a>.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload