有以下视图模型(拿出一些部分)
function ProjectViewModel() {
var self = this;
self.openProjects = ko.observableArray();
self.currentPhase = ko.observable();
self.filteredProjects = ko.computed(function() {
return ko.utils.arrayFilter(self.openProjects(), function(ProjectModel) {
return ProjectModel.phase == self.currentPhase();
});
});
self.filter = function (phase) {
self.currentPhase(phase);
}
}
我想拥有项目总数的范围:
<span data-bind="text: openProjects().length + ' Projects'"></span>
然后我想为每个项目阶段显示一个跨度,显示该阶段的项目数量,但我不确定如何传递参数?
<span data-bind="text: filteredProjects().length"></span> // pass on for example 'Starting'
<span data-bind="text: filteredProjects().length"></span> // pass on for example 'Running'
<span data-bind="text: filteredProjects().length"></span> // pass on for example 'Closing'
在self.filteredProjects = ko.computed(function() {
中的我可以简单地对值进行硬编码并重复三次代码,但必须有更好的方法吗?即用某个参数绑定self.currentPhase?
答案 0 :(得分:0)
您的情况可能与此处不匹配
self.filteredProjects = ko.computed(function() {
return ko.utils.arrayFilter(self.openProjects(), function(ProjectModel) {
return ProjectModel.phase == self.currentPhase();
});
});
尝试这样做
return ProjectModel.phase() == self.currentPhase();
如果您知道阶段是可观察的
答案 1 :(得分:0)
您可以使用工厂方法构建ko.computed
。
self.filteredProjects = function(phase) {
// use currentPhase as default
var filterPhase = phase || self.currentPhase();
return ko.computed(function() {
return ko.utils.arrayFilter(self.openProjects(), function(ProjectModel) {
return ProjectModel.phase == filterPhase;
});
});
};
此绑定使用currentPhase
<span data-bind="text: filteredProjects()().length"></span>
这些绑定使用&#39;开始&#39;,&#39;运行&#39;和&#39;结束&#39;
<span data-bind="text: filteredProjects('Starting')().length"></span>
<span data-bind="text: filteredProjects('Running')().length"></span>
<span data-bind="text: filteredProjects('Closing')().length"></span>