I am working on knockout bindings.. I have knockout sorting to implement and i have done this way..
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;
}
and my html code is like this:
<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>
I want to refactor the sort function to something like this..
_
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";
}
}
};
But it didnt work out as, it was saying that the a and b parameters are not available.. can anyone please tell me how to separe the logic from the anonymous function