knockoutjs ObservableArrays和sort函数:UI未更新 [英] knockoutjs ObservableArrays and sort function: UI is not updated
问题描述
在我的viewmodel中,我有一个knockoutjs ObserableArray。在我初始化ViewModel之后,它成功地绑定了数据。然后,我需要做的是对集合进行排序。
In my viewmodel, I have a knockoutjs ObserableArray. Just after I initialized the ViewModel, it binds the data successfully. Then, what I need to do is to sort the collection.
$.each(vm.searchResults(), function (i, property) {
console.log(property.Name());
});
vm.searchResults().sort(function (a, b) {
return a.Name().toLowerCase() > b.Name().toLowerCase() ? 1 : -1;
});
$.each(vm.searchResults(), function (i, property) {
console.log(property.Name());
});
如您所见,我将元素的名称输出到控制台以查看之前的订单和排序后。排序工作得很好。问题在于UI更新。不知何故,UI未更新。
As you can see, I output the Name of the element to the console to see the order before and after the sorting. The sorting works just fine. The problem is with the UI update. Somehow, the UI is not updated.
然后,尝试使用以下代码从数组中删除记录,以查看UI是否会响应:
Then, try to remove a record from the array with the following code to see if the UI will respond to that or not:
vm.searchResults().shift();
用户界面保持不变,并且没有再次更新。这会有什么问题?
The UI stays the the same and didn't update again. What would be the problem here?
编辑:
这是一个示例案例: http://jsfiddle.net/tugberk/KLpwP/
同样的问题也在这里。
编辑:
我解决了这个问题所示的问题: http://jsfiddle.net/tugberk / KLpwP / 16 / 但我仍然不确定为什么它起初像我一样努力。
I solved the problem as shown in this sample: http://jsfiddle.net/tugberk/KLpwP/16/ But I am still not sure why it worked as I tried at first.
推荐答案
你当你要对它进行排序时,我会解开可观察的数组。这是导致问题,因为KO无法跟踪数组被更改。 ko.observableArray()
具有相同签名的 sort
函数,它将通知observable的订阅者它已被更改。解决方案非常简单:删除大括号 vm.searchResults()。sort
=> vm.searchResults.sort
。查看我的示例: http://jsfiddle.net/RbX86/
You're unwrapping observable array when you are going to sort it. This is causes problem, because KO can't track array was changed. ko.observableArray()
has sort
function with same signature and it will notify observable's subscribers that it has been changed. Solution is very simple: remove braces vm.searchResults().sort
=> vm.searchResults.sort
. Checkout my example: http://jsfiddle.net/RbX86/
另一种告诉KO数组有变化的方法 - 在使用数组进行操作后调用 valueHasMutated
方法。请查看此示例: http://jsfiddle.net/RbX86/1/
当您需要在数组中进行许多更改并且只想刷新UI一次时,方法非常好。
Another way to tell KO that array has changes - call valueHasMutated
method after manipulations with array. Please review this sample: http://jsfiddle.net/RbX86/1/
This approach is very good when you need to make many changes in your array and you want to refresh UI only one time.
这篇关于knockoutjs ObservableArrays和sort函数:UI未更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!