我有兩個按鈕,按播放器名稱和ID排序。 iam使用兩種函數來進行每種排序。Javascript Knockout,從值中查找屬性名稱
<ul data-bind="template: { name: 'playerstmpl', foreach: players }"></ul>
<hr/>
<button data-bind="click: sortbyPlayer">Sort by Player</button>
<button data-bind="click: sortbyId">Sort by Id</button>
<script id="playerstmpl" type="text/html">
<li> <span data-bind = "text: id"> </span>
<input data-bind="value: FirstName" /> </li>
</script>
<script type="text/javascript">
function Player(id, name) {
return {
id: ko.observable(id),
FirstName: ko.observable(name)
};
}
var viewModel = {
players: ko.observableArray([
new Player(64, "Yuvi"),
new Player(22, "Gayle"),
new Player(91, "Adam"),
new Player(19, "Flintoff"),
new Player(56, "Malinga")])
};
viewModel.sortbyPlayer = function() {
var unsorted = viewModel.players();
viewModel.players(unsorted.sort(viewModel.sortFunction = function (a, b) {
return a.FirstName().toLowerCase() < b.FirstName().toLowerCase() ? -1 : 1;
}));
};
viewModel.sortbyId = function() {
var unsortedId = viewModel.players();
viewModel.players(unsortedId.sort(viewModel.sortFunction = function (a, b) {
return a.id() < b.id() ? -1 : 1;
}));
};
ko.applyBindings(viewModel);
</script>
我試着去尋找這是在函數傳遞的特性,這樣我可以合併兩個功能於one..like
viewModel.sortbyPlayer = function() {
var unsorted = viewModel.players();
viewModel.players(unsorted.sort(viewModel.sortFunction = function (a, b) {
if (Player[a] == "FirstName") { // is string
return a.FirstName().toLowerCase() < b.FirstName().toLowerCase() ? -1 : 1;
}
else {
return a.id() < b.id() ? -1 : 1;
}
}));
};
反正有一個功能排序做。謝謝
你的排序功能應當兩個輸入值相同時返回'0'。 – Arjan 2013-04-24 05:10:17