[英]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.