• KnockoutJs学习笔记(四)


    由于Writable computed observablesHow dependency tracking works的要求相对较高,我先跳过这两篇,学习Pure computed observables

    Pure computed observables相对于一般的computed observables,在性能和存储上有优势,这是因为pure computed observables在不存在订阅者的时候是不会保持订阅关系的。这也使得pure computed observables有如下两点特点:

    • 可以防止没有被订阅的computed observables的存储泄露。
    • 可以降低因重复计算未被订阅的computed observables而造成的运算过载。

    一个pure computed observable能够依据它是否拥有订阅者而自动地在两种状态下切换:

    1. 当不存在订阅者的时候,pure computed observable会进入休眠状态,此时的它,会关闭所有依赖于它的订阅关系,同时也不会再追踪它所关联的observables。一旦处于休眠状态的computed observable的值被读取的话,它就需要重新计算以便以确保值得正确性。
    2. 当它拥有订阅者的时候,pure computed observable会进入监听状态。一旦进入监听状态,它会立即调用它的function和订阅程序来追踪它所关联的observables。在这种状态下,pure computed observables和普通的computed observables无异。更为详细的内容需参考How dependency tracking works部分

    按照文档的说明,选择pure computed observables有两条原则。一是computed observable在运算的时候不能产生副作用(不能对其他的observables产生影响);二是computed observable的值应该仅仅依赖于它所关联的observables的值,而不是其他隐含的信息。

    Pure computed observables有两种定义方式:

    1 this.fullName = ko.pureComputed(function() {
    2     return this.firtstName() + " " + this.lastName();
    3 }, this);

    或是:

    1 this.fullName = ko.computed(function() {
    2     return this.firstName() + " " + this.lastName();
    3 }, this, { pure: true });

    另外,在稳固的(persistent)view model中使用pure computed observables能够提供运算性能上提升,在临时的(temporary)view model中使用pure computed observables能够提供存储管理上的提升。

    有关性能方面的问题,留作以后研究

  • 相关阅读:
    leetcode——33.搜索旋转排序数组
    leetcode——80.删除排序数组中的重复项2
    leetcode——26.删除排序数组中的重复项
    leetcode——18.四数之和
    leetcode——42.接雨水
    leetcode——11.盛最多水的容器
    leetcode——16.最接近的三数之和
    leetcode——15.三数之和
    leetcode——1002.查找常用字符
    004 linux学习:【第4篇】之nginx
  • 原文地址:https://www.cnblogs.com/charlieyuki/p/3928902.html
Copyright © 2020-2023  润新知