文章出處

Pure computed observables

Pure computed observables是KO在3.2.0版本中推出的。她相對于之前的ComputedObservables有很多改進:

  • 防止內存泄漏
  • 減少計算開銷

在PureComputed函數中,隨著相關監控屬性值變化的時候,在兩種狀態之間切換。

  1. 每當它沒有 值變化的時候,它處于睡眠狀態。當進入睡眠狀態時,其配置的所有訂閱它的依賴。在這種狀態下,它不會訂閱任何監控屬性。如果當它被讀取,返回的也是睡眠狀態的值。

  2. 每當它 值變化的時候,它將處于監聽狀態。當進入監聽狀態,它會立即訂閱所有依賴。在這種狀態下,它的運作就像一個普通的計算監控屬性。

語法:

Pure computed observables:

this.fullName = ko.pureComputed(function() {
    return this.firstName() + " " + this.lastName();
}, this);

原始的Computed observables加上pure參數后的等同寫法:

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

使用Pure computed observables

在一個簡單的向導界面的實例中,Pure computed observables僅在最后的步驟綁定到視圖,所以當該步驟有效時僅更新。fullName

 

First name:

Last name:

Prefix:

Hello, !

UI源碼:

<div class="log" data-bind="text: computedLog"></div>
<!--ko if: step() == 0-->
    <p>First name: <input data-bind="textInput: firstName" /></p>
<!--/ko-->
<!--ko if: step() == 1-->
    <p>Last name: <input data-bind="textInput: lastName" /></p>
<!--/ko-->
<!--ko if: step() == 2-->
    <div>Prefix: <select data-bind="value: prefix, options: ['Mr.', 'Ms.','Mrs.','Dr.']"></select></div>
    <h2>Hello, <span data-bind="text: fullName"> </span>!</h2>
<!--/ko-->
<p><button type="button" data-bind="click: next">Next</button></p>

視圖模型源碼:

function AppData() {
    this.firstName = ko.observable('John');
    this.lastName = ko.observable('Burns');
    this.prefix = ko.observable('Dr.');
    this.computedLog = ko.observable('Log: ');
    this.fullName = ko.pureComputed(function () {
        var value = this.prefix() + " " + this.firstName() + " " + this.lastName();
        // Normally, you should avoid writing to observables within a pure computed 
        // observable (avoiding side effects). But this example is meant to demonstrate 
        // its internal workings, and writing a log is a good way to do so.
        this.computedLog(this.computedLog.peek() + value + '; ');
        return value;
    }, this);
 
    this.step = ko.observable(0);
    this.next = function () {
        this.step(this.step() === 2 ? 0 : this.step()+1);
    };
};
ko.applyBindings(new AppData());

確定一個屬性是不是Pure computed observables

KO提供了ko.isPureComputed函數,幫助確定監控屬性是不是Pure computed observables。

var result = {};
ko.utils.objectForEach(myObject, function (name, value) {
    if (!ko.isComputed(value) || ko.isPureComputed(value)) {
        result[name] = value;
    }
});

文章列表




Avast logo

Avast 防毒軟體已檢查此封電子郵件的病毒。
www.avast.com


arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()