簡體   English   中英

在foreach中刪除動態CSS綁定

[英]Knockout dynamic css binding in foreach

我正在嘗試使用淘汰賽來創建服務器端排序和分頁的html表網格。

我的工作基於淘汰賽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類不會更新。

您是否知道我在做什么錯?

css類不會更新,因為$parent.sortClass($data)意味着在首次應用綁定時僅調用一次sortClass函數。 要在單擊時更新它,可以將sortClass轉換為可計算的可觀察值,如下面的代碼所示(小提琴: 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())

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM