我正在尝试按online
属性对用户进行排序:
var userViewModel = function(data){
var self = this;
self.name = ko.observable(data.name);
self.online = ko.observable(data.online);
};
var mainViewModel = function(data){
var self = this;
self.users = ko.observableArray(data.users.map(function(user){
var model = new userViewModel(user);
model.online.subscribe(function(){
self.users.sort(function (a, b) { return b.online() - a.online(); });
});
return model;
}));
self.users.subscribe(function(){
console.log('users have changed');
});
};
HTML:
<div data-bind="foreach: users">
Online: <div data-bind="text: online"></div>
<div data-bind="text: name"></div>
</div>
一切正常,但是在更改在线属性时,会对用户进行排序并记录“用户已更改”。我知道它发生是因为我正在更改原始数组。我想要的是 - 不要改变原始数组,只是显示它排序(就像角度一样)