2013-04-29 42 views
0

我有表與列的敲除綁定。我試圖爲每列實現表格分類。 的看法是這樣的:使用模板排序表

<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> 
          </tr> 
          <tbody data-bind="template: { name: 'StudentNote', foreach: notes }"></tbody> 
         </table> 
         <script type="text/html" id="StudentNote"> 
          <tr class="even"> 
           <td><span data-bind="text: CreatedDate"></span></td> 
           <td><span data-bind="text: Type"></span></td> 
           <td><span data-bind="text: Category"></span></td> 
           <td><span data-bind="text: AddedBy"></span></td> 
          </tr> 
         </script> 

和JavaScript是這樣的:

function notesViewModel() { 
    var _this = {}; 
    _this.colName = "CreatedDate"; 
    _this.sortOrder = "desc"; 
    _this.notes = ko.observableArray(); 
_this.SortItems = function (ColumnName) { 

     var newNotes = _this.notes(); 
     if (_this.sortOrder === "desc") { 
      this.notes(newNotes.sort(notesViewModel._getSortFunction = function (a, b) { 
       _this.sortOrder = "asc"; 
       return a[ColumnName] < b[ColumnName] ? -1 : 1; 
      })); 

     } else { 
      this.notes(newNotes.sort(notesViewModel._getSortFunction = function (a, b) { 
       _this.sortOrder = "desc"; 
       return a[ColumnName] > b[ColumnName] ? -1 : 1; 
      })); 
     } 
    }; 
ko.applyBindings(_this, $("body").get(0)); 
return _this; 

即使它的排序,它只是升序和降序之間切換在每個列的,但不能識別哪些列被排序。如何做每一列排序..

回答

1

試試這個:

function notesViewModel() { 
    var _this = {}; 
    _this.colName = "CreatedDate"; 
    _this.sortOrder = 1; 
    _this.notes = ko.observableArray(); 
    _this.SortItems = function (ColumnName) { 
     if(ColumnName == _this.colName) 
      _this.sortOrder = _this.sortOrder * -1; 
     else 
      _this.colName = ColumnName; 

     _this.notes.sort(function (a, b) { 
      return (a[ColumnName] < b[ColumnName] ? -1 : 1) * _this.sortOrder; 
     }); 
    }; 
    ko.applyBindings(_this, $("body").get(0)); 
    return _this; 
} 
+0

感謝可能的答覆..但是,如果我點擊一列和排序他們升序和點擊其他它排序後降序(意味着切換升序和降序無論列)..我期望看到第二列上升以及 – user2288976 2013-04-29 04:10:08

+0

我已經調整了代碼,以便在更改列時保留排序順序。 – RodneyTrotter 2013-04-29 04:17:18

+0

新的代碼不會降序排序.. – user2288976 2013-04-29 04:58:44