afterRender模板调用似乎是作为computedObservables执行的.为什么以及如何解决? [英] The afterRender template call seems to be executed as a computedObservables. Why and how to fix it?
问题描述
所以这个问题是我之前的问题淘汰条件本机模板会在什么条件下重新渲染
So this question follows on from my previous question Under what conditions does a Knockout native template re-render
经过一番调查,似乎如果模板定义了afterRender
函数并且afterRender
函数引用了零件模型,那么,如果随后更改了该模型的那一部分,则会再次调用afterRender
函数.
After some investigation, it seems that if a template defines an afterRender
function and that afterRender
function references a part model then, if that part of the model is subsequently altered, the afterRender
function is called again.
此行为似乎类似于computedObservables
(也称为dependentObservables
),在该行为中,剔除会跟踪模型所依赖的部分,然后只要其中一个值依赖于更改,就重新运行computedObservables
.
This behaviour seems similar to computedObservables
(aka dependentObservables
) where knockout tracks which parts of the model it depends on and then re-runs the computedObservables
whenever one of the values it depends on changes.
为了证明这一点,我写了一个jsFiddle: http://jsfiddle.net/unklefolk/nczCt /1/
To demonstrate this I have written a jsFiddle: http://jsfiddle.net/unklefolk/nczCt/1/
按预期,渲染视图时将调用afterRender函数.但是,如果单击复选框,则使用viewModel.selectedPet().pet().IsHappy()
As expected the afterRender function is called when the view is rendered. However, if you click the checkbox, the afterRender function is run again as it uses viewModel.selectedPet().pet().IsHappy()
这对我来说没有意义.所以我的问题是:
This does not make sense to me. So my question is:
- 这是重新运行
afterRender
函数的错误吗? - 如何确保
afterRender
函数仅运行一次?
- Is this a bug that the
afterRender
function is being re-run? - How can I ensure that the
afterRender
function is only run once?
谢谢.
推荐答案
Knockout使用已计算的可观察值将绑定的执行包装在元素上.这是当依赖项更改时再次触发绑定的方式(此
Knockout uses a computed observable to wrap the execution of the bindings on an element. This is how the bindings are triggered again when a dependency changes (this link might help explain further.
当前,没有将afterRender
代码添加到这些依赖项中.如果您的情况不希望这样做,那么有两种方法可以防止这种情况发生.
Currently, the afterRender
code is not excluded from adding to these dependencies. If this is not desirable for your scenario, then there are a couple of ways to prevent it.
- 在
setTimeout
中运行代码:如 http://jsfiddle.net/rniemeyer/nczCt /2/ - 将其代码包装在自己可计算的可观察范围内,然后立即将其处置: http://jsfiddle.net /rniemeyer/nczCt/3/(我现在这样做是为了避免setTimeout)
- 在KO 2.2中,您将能够在可观察对象上使用新的
peek
函数,该函数使您无需创建依赖项即可获取值.
- run your code in a
setTimeout
: like http://jsfiddle.net/rniemeyer/nczCt/2/ - wrap your code in its own computed observable that you immediately dispose like: http://jsfiddle.net/rniemeyer/nczCt/3/ (I would do this for now to avoid the setTimeout)
- In KO 2.2 you will be able to use the new
peek
function on observables that allows you to get the value without creating a dependency.
这篇关于afterRender模板调用似乎是作为computedObservables执行的.为什么以及如何解决?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!