为什么子视图模型中的函数会导致在父视图模型中计算的结果触发? [英] Why does a function in a child view model causes a computed in the parent view model to fire?
问题描述
按以下代码执行按钮有两件事:它在嵌套视图模型中执行一个功能,并在父视图模型中执行一个computed
来执行.
Pushing the button in the following code does 2 things: It executes a function in a nested view model, and also makes a computed
in the parent view model to execute.
var MasterViewModel = function () {
var self = this;
self.nested = new FirstViewModel();
self.func = ko.computed (function() {
var items = self.nested.array();
alert("executed");
});
}
var FirstViewModel = function () {
var self = this;
self.array = ko.observableArray([]);
self.push = function () {
self.array.push(new SecondViewModel());
alert("pushed");
}
}
var SecondViewModel = function () {
var self = this;
self.z = ko.observable();
}
var mvm = new MasterViewModel();
ko.applyBindings(mvm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="with: nested">
<button data-bind="text: 'push me', click: push"></button>
</div>
但是,如果将computed
更改为简单功能,则按下按钮时它不会执行.为什么?
However, if the computed
is changed to a simple function, it doesn't execute when the button is pushed. Why?
var MasterViewModel = function () {
var self = this;
self.nested = new FirstViewModel();
self.func = function() {
var items = self.nested.array();
alert("executed");
};
}
var FirstViewModel = function () {
var self = this;
self.array = ko.observableArray([]);
self.push = function () {
self.array.push(new SecondViewModel());
alert("pushed");
}
}
var SecondViewModel = function () {
var self = this;
self.z = ko.observable();
}
var mvm = new MasterViewModel();
ko.applyBindings(mvm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<div data-bind="with: nested">
<button data-bind="text: 'push me', click: push"></button>
</div>
推荐答案
首先:<div data-bind="func">
中的data-bind="func"
为我举起了红旗.通常,绑定的格式为bindingName: boundValue
.
First: The data-bind="func"
in <div data-bind="func">
raises a red flag for me. Normally a binding is in the form bindingName: boundValue
.
但是回答这个问题:每当计算值依赖的可观察值发生变化时,都会重新计算该值.您要在FirstViewModel#push
中更改self.array
,因此自然会重新计算在MasterViewModel
中使用它的计算值(作为self.nested.array
).
But answering the question: A computed's value is recomputed whenever any of the observables it depends on is changed. You're changing self.array
in FirstViewModel#push
, so naturally the value of the computed that uses it in MasterViewModel
(as self.nested.array
) is recomputed.
这篇关于为什么子视图模型中的函数会导致在父视图模型中计算的结果触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!