KnockoutJS 3.X API 第三章 计算监控属性(4)Pure computed observables

2022-12-26,,,,

Pure computed observables

Pure computed observables是KO在3.2.0版本中推出的。她相对于之前的ComputedObservables有很多改进:
防止内存泄漏
减少计算开销

在PureComputed函数中,随着相关监控属性值变化的时候,在两种状态之间切换。

    每当它没有 值变化的时候,它处于睡眠状态。当进入睡眠状态时,其配置的所有订阅它的依赖。在这种状态下,它不会订阅任何监控属性。如果当它被读取,返回的也是睡眠状态的值。

    每当它 值变化的时候,它将处于监听状态。当进入监听状态,它会立即订阅所有依赖。在这种状态下,它的运作就像一个普通的计算监控属性。

语法:

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

Next

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;
}
});

KnockoutJS 3.X API 第三章 计算监控属性(4)Pure computed observables的相关教程结束。

《KnockoutJS 3.X API 第三章 计算监控属性(4)Pure computed observables.doc》

下载本文的Word格式文档,以方便收藏与打印。