gpt4 book ai didi

javascript - 在 Knockout.js 中,如何对数组进行排序

转载 作者:行者123 更新时间:2023-11-28 20:45:41 25 4
gpt4 key购买 nike

在 ViewModel 中,我有一个 observableArray 和一个计算,它们返回 View 中管理的数组:

var operators = ko.observableArray([]);
var records = ko.computed(function () {
return operators();
});

这是我的排序方法;

Order = function (data, event, colName) {
var th = $('#th-' + colName),
attr = th.data('sort');

setAttribute(th, attr); //switch data-sort between 'asc' and 'desc'

if (attr === 'asc') {
operators = operators.sort(function (a, b) {
return (a.fullname === b.fullname) ? 0 : (a.fullname < b.fullname ? -1 : 1);
});
}
else {
operators = operators.sort(function (a, b) {
return (a.fullname === b.fullname) ? 0 : (a.fullname > b.fullname ? -1 : 1);
});
}
};

这是 View :

<table id="table-hour">
<thead>
<tr>
<th data-bind="click: function(data, event) { Order(data, event, 'fullname')}" data-sort="asc" id="th-fullname">Fullname</th>
</tr>
</thead>
<tbody>
<!-- ko foreach: records -->
<tr>
<td>
<span data-bind="text: fullname"></span>
</td>
</tr>
<!-- /ko -->
</tbody>

嗯,排序功能就像一个魅力,实际上用浏览器调试我可以看到数组以两种方式排序,但 View 仅在第一次更新。我应该怎么做才能解决这个问题?

最佳答案

问题是,您需要更新 observableArray,并将数据放回到该数组中。

如果可观察对象未更新, View 也不会更新

看一下 JavaScript 排序功能 ( https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/sort )。

关于javascript - 在 Knockout.js 中,如何对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13509590/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com