【问题标题】:What's the proper way to apply ko.computeds (Knockout computeds) to a Durandal viewmodel?将 ko.computeds(Knockout 计算)应用于 Durandal 视图模型的正确方法是什么?
【发布时间】:2013-05-09 12:24:02
【问题描述】:

我是 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

错误截图

【问题讨论】:

  • 问题不在于您的撰写,而在于您的视图。请张贴查看代码你在哪里使用completedCount
  • 添加了一个项目链接以及一个直接指向视图的链接。
  • 我看不出您的代码或 HTML 有什么问题;如果它与your other question 的问题相同,您可能只是误解了控制台告诉您的内容。可以再发一张截图吗?
  • 您对控制台消息的误解可能是正确的。我是 Knockout 和 Durandal 的新手。我在上面附上了另一个截图。谢谢。
  • 是的,你们都很好。如果您在计算时遇到错误,它也会在控制台中显示为红色。

标签: javascript knockout.js viewmodel amd durandal


【解决方案1】:

首先定义 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;

【讨论】:

【解决方案2】:

我的问题似乎是对控制台消息和 Knockout 工作原理的误解。你可以在Durandal TodoMVC - Cannot write a value to a ko.computed看到解释。​​

【讨论】:

    猜你喜欢
    • 2015-07-29
    • 1970-01-01
    • 2018-05-30
    • 2017-02-09
    • 1970-01-01
    • 1970-01-01
    • 2012-05-07
    • 2021-05-29
    • 1970-01-01
    相关资源
    最近更新 更多