0

我是 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.")

compose 方法请求视图模型和视图:

<!--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

错误截图 在此处输入图像描述

4

2 回答 2

0

我的问题似乎是对控制台消息和 Knockout 工作原理的误解。您可以在Durandal TodoMVC - 无法将值写入 ko.computed中查看解释。

于 2013-05-16T06:00:20.903 回答
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;
于 2013-05-15T15:18:14.187 回答