javascript - Knockout observableArray sort not reflecting in the UI (foreach binding) -
i'm adding data tag list grid (by checking rows of data). when happens, want tag list sorted (for example sorted alphabetically name).
the sort result has reflect in ui, i've tried not work in case.
here's fiddle example: http://jsfiddle.net/hlplobo2/5/
in order make sure it's sorted, i'm calling sortpersonsalphabetically
function on foreach
afteradd
callback:
<div class="tag-list" data-bind="foreach: { data: tags, as: 'tag', afteradd: sortpersonsalphabetically }"> <div class="tag-item"> <span class="tag-item-value tag-item-value-name" data-bind="text: tag.name"></span> <span class="tag-item-separator">:</span> <span class="tag-item-value tag-item-value-age" data-bind="text: tag.age"></span> </div> </div>
but strangely works after adding item ("second selection").
in fiddle example provided, i've added <pre>
tag clear array sorted, yet it's not reflected in tag list ui.
i've tried wrapping sort function in settimeout
of 1ms delay , seems fix it, visible flicker, in opinion, not acceptable , it's more of hack.
is there clean way ?
afteradd intended updating dom in response changes in data, not making further changes data. result getting weird, though, agree.
i recommend use computed generate sorted tags,
self.sortedtags = ko.computed(function () { var data = self.tags(); return data.sort(function(left, right) { return left.name == right.name ? 0 : (left.name < right.name ? -1 : 1); }); });
and display in foreach:
<div class="tag-list" data-bind="foreach: { data: sortedtags, as: 'tag' }">
Comments
Post a Comment