微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

knockout.js – KnockoutJS – 如何使用条件语句工作的计算观察值

KnockoutJS具有计算可观察量的概念,它是依赖于一个或多个可观察值的函数.淘汰赛能够到 determine the dependencies of a computed observable as described in the docs

Whenever you declare a computed observable,KO immediately invokes its
evaluator function to get its initial value. While your evaluator
function is running,KO keeps a log of any observables (or computed
observables) that your evaluator reads the value of.

现在,我不明白的是,如果您的计算的observable包含条件逻辑,它是如何工作的.如果Knockout调用评估器函数,肯定有条件逻辑可能导致可观察的函数,该函数取决于不被调用

我创建了这个小提琴来测试:

http://jsfiddle.net/bJK98/

var viewmodel = function(first,last) {
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);
    this.condition = ko.observable(false);

    // at the point of evaluation of this computed observabled,'condition'
    // will be false,yet the dependecy to both firstName and lastName is
    // identified
    this.fullName = ko.computed(function() {
        return this.condition() ? this.firstName() : this.lastName();
    },this);
};

但是,不知何故Knockout正确地识别了对firstName和lastName的依赖.

有人可以解释一下吗

解决方法

每次重新评估dependentObservable时,会再次跟踪依赖关系.所以,如果你有条件逻辑,那么没有命中的分支不会对依赖有贡献.

在您的小提琴中,如果您编辑firstName,则在切换条件之前,该值不会更新.在这一点上,lastName不再是依赖关系,所以对它的更改不会触发dependentObservable.

它不是真的比原来的描述更复杂.要记住的基本事情是每次重新评估时会记录依赖关系.

原文地址:https://www.jb51.cc/js/151895.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐