为什么子视图模型中的函数会导致父视图模型中的函数被触发? [英] Why does a function in a child view model causes a function in the parent view model to fire?

查看:72
本文介绍了为什么子视图模型中的函数会导致父视图模型中的函数被触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对此在以下代码中,func是绑定到父级div的简单函数.自然,在加载文档时会触发,但在按下按钮时也会触发.

On the following code, func is a simple function that's bounded to a parent div. Naturally, it fires when document loads, but it also fires when the button is pressed.

正如对链接问题的回答所解释的那样,我认为只有在func会是computed时,这种情况才会发生(因为只要它依赖的任何可观察变量都被更改,它的值就会被重新计算),但是我现在看到它是通过一个简单的函数发生的.

As explained on the answer to the linked question, I thought this can happen only if func would have been a computed (since it's value is recomputed whenever any of the observables it depends on is changed), but I now see it happens with a simple function.

为什么?

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="value: func()">
     <div data-bind="with: nested">
       <button data-bind="text: 'push me', click: push"></button>
     </div>
  </div>

推荐答案

KO适用于可观察对象(如您所知).当您为绑定值提供 expression 而不是仅对observable的引用时,KO在应用绑定时会有效地将该表达式包装在计算值中.因此:

KO works with observables (as you know). When you provide an expression for a binding value rather than just a reference to an observable, KO effectively wraps that expression in a computed when applying the bindings. So this:

<div data-bind="value: func()"></div>

...实际上与此相同:

...is effectively the same as this:

<div data-bind="value: computed"></div>

... KO在幕后创建computed的地方是这样的:

...where KO is creating computed behind the scenes something like this:

computed = ko.pureComputed(function() {
    return func();
});

并且由于func使用可观察的self.nested.array的值,因此KO的更改跟踪会在计算计算值时看到并记住该事实,因此它知道在self.nested.array更改时重新计算计算值.

And since func uses the value of the observable self.nested.array, KO's change tracking sees and remembers that fact when it computes the computed's value, so it knows to recompute the computed when self.nested.array changes.

这篇关于为什么子视图模型中的函数会导致父视图模型中的函数被触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆