答案 0 :(得分:2)
您必须使用value
绑定而不是change
事件:
<select data-bind="value: sortMode,
options: headers,
optionsText: 'title'"></select>
然后,在您的viewmodel中,您可以订阅sortMode
:
var self = this;
this.sortMode = ko.observable("title");
this.sort = function() {
var sortProperty = self.sortMode();
// Logic to sort by `sortProperty` goes here:
// ...
};
this.sortMode.subscribe(this.sort);
点击此处查看我的建议:https://jsfiddle.net/u8tLLrLb/
查看代码,我建议使self.activeSort
成为可观察的,引入名为pureComputed
的{{1}}属性和名为{{1}的sortMethod
数组}:
pureComputed
然后,sortedMovies
的数据绑定将是:
self.activeSort = ko.observable(self.headers[0]);
self.sortMethod = ko.pureComputed(function() {
var sortType = self.activeSort().sortType;
switch (sortType) { /* return a function(a,b) { } */ }
});
self.sortedMovies = ko.pureComputed(function() {
return self.movies().sort(self.sortMethod());
});
更改此设置将更新<select>
,这将更新<select data-bind="value: activeSort,
options: headers,
optionsText: 'title'"></select>
。