我是Durandal的新手,并且在视图模型中应用ko.computed方法并没有太多运气。有人能告诉我正确的语法或模式是什么吗?
您可以在https://github.com/robksawyer/durandal-todo/blob/master/views/todos.html找到整个项目。
我应用的每个计算在绑定期间都会收到以下错误。
Error("Cannot write a value to a ko.computed unless you specify a 'write' option. If you wish to read the current value, don't pass any parameters.")
撰写请求视图模型和视图的方法:
<!--ko compose: {
model: router.activeItem, //wiring the router
afterCompose: router.afterCompose, //wiring the router
cacheViews: false, //telling composition to keep views in the dom, and reuse them (only a good idea with singleton view models)
transition: 'fadein'
}--><!--/ko-->
视图模型:
// count of all completed todos
var completedCount = ko.computed(function () {
return ko.utils.arrayFilter(todos(), function (todo) {
return todo.completed();
}).length;
});
查看 https://github.com/robksawyer/durandal-todo/blob/master/views/todos.html
错误截图
答案 0 :(得分:0)
首先定义vm单例然后添加ko.computed方法很可能会处理该错误消息。
var vm = {
current : current,
todos: todos,
... // remove ko.computeds from the singleton
};
vm.completedCount = ko.computed(function () {
return ko.utils.arrayFilter(todos(), function (todo) {
return todo.completed();
}).length;
}, vm);
// add other ko.computeds
return vm;
答案 1 :(得分:0)
我的问题似乎是对控制台消息的错误解释以及Knockout的工作原理。您可以在Durandal TodoMVC - Cannot write a value to a ko.computed找到解释。