[英]refactoring anonymous function javascript
我正在研究剔除綁定..我已經實施剔除排序,並且我已經這樣做。
function notesViewModel() {
_this.colName = "CreatedDate";
_this.sortOrder = "desc";
_this.notes = ko.observableArray();
_this.SortItems = function (colname) {
var newNotes = _this.notes();
if (_this.sortOrder === "desc") {
this.notes(newNotes.sort(notesViewModel._getSortFunction = function (a, b) {
return a[colname] < b[colname] ? -1 : 1;
}));
switchSortOrder();
} else {
this.notes(newNotes.sort(notesViewModel._getSortFunction = function (a, b) {
return a[colname] > b[colname] ? -1 : 1;
}));
switchSortOrder();
}
};
function switchSortOrder() {
if (_this.sortOrder === "asc") {
_this.sortOrder = "desc";
} else {
_this.sortOrder = "asc";
}
}
ko.applyBindings(_this, $("body").get(0));
return _this;
}
和我的HTML代碼是這樣的:
<table id="notes" class="notes_table">
<tr class="head">
<th data-bind='click: function() { SortItems("CreatedDate")}'>
<span>Date</span>
</th>
<th data-bind='click: function() { SortItems("Type")}'>
<span>Type</span>
</th>
<th data-bind='click: function() { SortItems("Category")}'>
<span>Category</span>
</th>
<th data-bind='click: function() {SortItems("AddedBy")}'>
<span>Added by</span>
</th>
<th>
<span>Alerts</span>
</th>
<th></th>
</tr>
<tbody data-bind="template: { name: 'StudentNote', foreach: notes }"></tbody>
</table>
我想將排序功能重構為這樣。
_
this.SortItems = function (colname) {
var newNotes = _this.notes();
this.notes(newNotes.sort(notesViewModel._getSortFunction = compareFunction (a, b,_this.sortOrder)));
function comparerFunction(a,b,sortOrder)
{
if(sortOrder === "desc")
{
return a[colname] < b[colname] ? -1 : 1;
_this.sortOrder = "asc";
}
else
{
return a[colname] > b[colname] ? -1 : 1;
_this.sortOrder = "desc";
}
}
};
但是它沒有解決,因為它說a和b參數不可用..任何人都可以告訴我如何從匿名函數中分離邏輯
您似乎對什么是匿名函數感到困惑。
(我認為)您要嘗試的是基於“ this”的字段“ sortOrder”具有一個可用於對升序和降序進行排序的函數。
您的代碼有幾個問題:
這段代碼符合您的要求,盡管我尚未對其進行測試,並且不知道您使用的框架。 它將在調用sort之前將sortOrder存儲在外部函數中,以便內部函數可以使用它。
this.SortItems = function (colname) {
var sortOrder = this.sortOrder; // make sortOrder available to the sort function
this.notes(_this.notes().sort(
function (a, b) {
return ((sortOrder === "desc") ? 1 : -1) * ((a[colname] < b[colname]) ? -1 : 1);
}));
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.