2013-04-26 69 views
0

我在淘汰赛绑定工作..我有淘汰赛排序,以实现和我做这样..重构匿名函数的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参数不可用..谁能告诉我如何从匿名函数

回答

1

separe逻辑它看起来像你是一个对于什么匿名函数有点困惑。

你试图做的是什么(我认为)有一个函数可以用于排序升序和降序,基于'this'的字段“sortOrder”。

有几个问题与您的代码:

  • 首先,你调用该函数,而不是将其保存到this.sortOrder的。这就是为什么'a'和'b'不可用,这个函数只能由排序算法调用。第二,'this'不会指向比较函数中的正确位置:要在JavaScript中定义'this'对象,您需要将该函数存储在对象(或原型)上,或者使用特殊的调用语义。 '这'在Javascript中很棘手,值得(重新)阅读一些教程以确保你理解它。
  • 最后,您在定义它之前调用compareFunction。

此代码是沿着你想要的,但我没有测试过,我不知道你使用的框架。它在调用排序之前在外部函数中存储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); 
    })); 
}; 
+0

您好斯蒂芬感谢您的回复..我使用asp.net MVC4 ..当我试图使用你建议的代码,它给我“表达staement不分配或调用”。在排序逻辑行上。 – user2288976 2013-04-26 07:57:58

+0

我错过了'返回' – 2013-04-27 00:00:09