- KnockoutJS 教程
- KnockoutJS - 首页
- KnockoutJS - 概述
- KnockoutJS - 环境设置
- KnockoutJS - 应用
- KnockoutJS - MVVM 框架
- KnockoutJS - 可观察对象
- 计算可观察对象
- KnockoutJS - 声明式绑定
- KnockoutJS - 依赖项跟踪
- KnockoutJS - 模板
- KnockoutJS - 组件
- KnockoutJS 资源
- KnockoutJS - 快速指南
- KnockoutJS - 资源
- KnockoutJS - 讨论
KnockoutJS - 依赖项跟踪
KnockoutJs 在值更新时会自动跟踪依赖项。它有一个名为依赖项跟踪器 (ko.dependencyDetection) 的单个对象,充当双方之间订阅依赖项的中间体。
以下是依赖项跟踪的算法。
步骤 1 - 每当你声明一个计算可观察对象时,KO 会立即调用其评估函数以获取其初始值。
步骤 2 - 为评估器读取的任何可观察对象设置订阅。在应用程序中,不再使用的旧订阅将被释放。
步骤 3 - KO 最终会通知更新的计算可观察对象。
示例
<!DOCTYPE html>
<html>
<head>
<title>KnockoutJS How Dependency Tracking Works</title>
<!-- CDN's-->
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type = "text/javascript"></script>
</head>
<body>
<div>
<form data-bind = "submit: addFruits">
<b>Add Fruits:</b>
<input data-bind = 'value: fruitToAdd, valueUpdate: "afterkeydown"'/>
<button type = "submit" data-bind = "enable: fruitToAdd().length > 0">Add</button>
<p><b>Your fruits list:</b></p>
<select multiple = "multiple" width = "50" data-bind = "options: fruits"> </select>
</form>
</div>
<script>
var Addfruit = function(fruits) {
this.fruits = ko.observableArray(fruits);
this.fruitToAdd = ko.observable("");
this.addFruits = function() {
if (this.fruitToAdd() != "") {
this.fruits.push(this.fruitToAdd()); // Adds a fruit
this.fruitToAdd(""); // Clears the text box
}
}.bind(this); // "this" is the view model
};
ko.applyBindings(new Addfruit(["Apple", "Orange", "Banana"]));
</script>
</body>
</html>
输出
让我们执行以下步骤来查看上述代码是如何工作的:
将上述代码保存在dependency_tracking.htm文件中。
在浏览器中打开此 HTML 文件。
输入任何水果名称并点击“添加”按钮。
使用 Peek 控制依赖项
可以使用peek函数访问计算可观察对象,而无需创建依赖项。它通过更新计算属性来控制可观察对象。
示例
<!DOCTYPE html>
<html>
<head>
<title>KnockoutJs Controlling Dependencies Using Peek</title>
<!-- CDN's-->
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.1.0.js"
type = "text/javascript"></script>
</head>
<body>
<div class = "logblock">
<h3>Computed Log</h3>
<pre class = "log" data-bind = "html: computedLog"></pre>
</div>
<script>
function AppData() {
this.firstName = ko.observable('John');
this.lastName = ko.observable('Burns');
this.computedLog = ko.observable('Log: ');
this.fullName = ko.computed(function () {
var value = this.firstName() + " " + this.lastName();
this.computedLog(this.computedLog.peek() + value + '; <br/>');
return value;
}, this);
this.step = ko.observable(0);
this.next = function () {
this.step(this.step() === 2 ? 0 : this.step()+1);
};
};
ko.applyBindings(new AppData());
</script>
</body>
</html>
输出
让我们执行以下步骤来查看上述代码是如何工作的:
将上述代码保存在dependency_tracking_peek.htm文件中。
在浏览器中打开此 HTML 文件。
观察结果
忽略计算依赖项中的依赖项
ko.ignoreDependencies函数有助于忽略你不想在计算依赖项中跟踪的那些依赖项。以下是其语法。
ko.ignoreDependencies( callback, callbackTarget, callbackArgs );
为什么循环依赖项没有意义
如果 KO 正在评估计算可观察对象,则它不会重新启动对依赖计算可观察对象的评估。因此,在你的依赖链中包含循环是没有意义的。
广告