在foreach中敲除动态css绑定

时间:2013-11-10 06:13:14

标签: javascript binding knockout.js

我正在尝试使用knockout创建一个带有服务器端排序和分页的html表格网格。

我的工作基于knockout simpleGrid示例。

到目前为止它工作但我有一个问题是绑定css类以显示选择哪个列进行排序。

这是我的代码:

html:

<thead>
  <tr data-bind="foreach: columns">
    <th data-bind="text: headerText, click: $parent.sortBy, css:  $parent.sortClass($data)"></th>
  </tr>
</thead>

淘汰赛阶段:

viewModel: function (configuration) {
  ...
  // Sort properties
  this.sortProperty = configuration.sortProperty;
  this.sortDirection = configuration.sortDirection;
  ...
  this.sortClass = function (data) {
    return data.propertyName == this.sortProperty() ? this.sortDirection() == 'ascending' ? 'sorting_asc' : 'sorting_desc' : 'sorting';
  };
}

我的主要淘汰课:

this.gridViewModel = new ko.simpleGrid.viewModel({
data: self.items,
pageSize: self.itemsPerPages,
totalItems: self.totalItems,
currentPage: self.currentPage,
sortProperty: self.sortProperty, 
sortDirection: self.sortDirection,
columns: [
    new ko.simpleGrid.columnModel({ headerText: "Name", rowText: "LastName", propertyName: "LastName" }),
    new ko.simpleGrid.columnModel({ headerText: "Date", rowText: "EnrollmentDate", propertyName: "EnrollmentDate" })
],
sortBy: function (data) {
    data.direction = data.direction == 'ascending' ? 'descending' : 'ascending';
    self.sortProperty = data.propertyName;
    self.sortDirection = data.direction;

    // Server call
    $.getGridData({
        url: apiUrl,
        start: self.itemStart,
        limit: self.itemsPerPages,
        column: data.propertyName,
        direction: data.direction,
        success: function (studentsJson) {
            // data binding
            self.items(studentsJson.gridData);
        }
    });
},
}

有了这个,第一次数据绑定我的css类正确应用。但是当我点击一列时,css类将不会更新。

你知道我做错了什么吗?

1 个答案:

答案 0 :(得分:3)

css类不会更新,因为$parent.sortClass($data)表示在首次应用绑定时只调用一次sortClass函数。要在click上更新它,您可以将sortClass转换为计算的observable,如下面的代码(小提琴:http://jsfiddle.net/ZxEK6/2/

var Parent = function(){
    var self = this;    
    self.columns = ko.observableArray([
        new Column("col1", self),
        new Column("col2", self),
        new Column("col3", self)
    ]);

}

var Column = function(headerText, parent){
    var self = this;
    self.parent = parent;
    self.sortDirection = ko.observable();
    self.headerText = ko.observable(headerText);
    self.sortClass = ko.computed(function(){
        if (!self.sortDirection()){
            return 'no_sorting';
        }
        return self.sortDirection() == 'ascending' ? 'sorting_asc' : 'sorting_desc';
    },self);

    self.sortBy = function(){
        if (!self.sortDirection()) {
            self.sortDirection('ascending');
        } else if (self.sortDirection() === 'ascending'){
            self.sortDirection('descending');
        } else {
            self.sortDirection('ascending');
        }
    }
}

ko.applyBindings(new Parent())