I'm totally new in knockout.
Good you help me to understand how I need to change this code:
<ol class="items" data-bind="foreach: getDisplayedItems()"> <li class="item"> <a class="simple" data-bind="html: label, attr: {href:url}, visible: count >= 1, css: { active: is_selected }"></a> <span class="count" data-bind="text: count"></span> </li> </ol>
to make it in alphabetically order?
Thanks for any tips Regards
CodePudding user response:
You could sort them in-place:
<ol class="items" data-bind="foreach: getDisplayedItems().sort((a, b) => ko.unwrap(a.label) < ko.unwrap(b.label) ? -1 : 1)">
<li class="item">
<a class="simple" data-bind="html: label, attr: {href:url}, visible: count >= 1, css: { active: is_selected }"></a>
<span class="count" data-bind="text: count"></span>
</li>
</ol>
but I think that's ugly, and it's not re-usable. It's better to make a new observable array that contains the items in the right order:
function App {
// the observable you already have
this.getDisplayedItems = ko.observableArray([...]);
// a computed observable based on that
this.getDisplayedItemsAlphabetical = ko.pureComputed(() => {
var itemsCopy = [...this.getDisplayedItems()];
return itemsCopy.sort((a, b) => ko.unwrap(a.label) < ko.unwrap(b.label) ? -1 : 1);
});
}
and
<ol class="items" data-bind="foreach: getDisplayedItemsAlphabetical">