在应用“可见”规则后调用函数

时间:2014-09-17 07:17:01

标签: javascript knockout.js

以下是上下文:我有一个div,其可见性与data-bind="visible: theBoolean"的可观察布尔值相关联。

当布尔值切换到true时,div变得可见,当我需要触发一个动作(刷新CodeMirror对象时),因为CodeMirror没有正确地渲染它和&#39} #39;在未显示的区域初始化。

在绑定效果完成后,我还没有找到调用函数的方法。我显然可以使用setTimeout,但我希望有更好的方法。

谢谢!

2 个答案:

答案 0 :(得分:2)

knockout template绑定支持afterRender回调(和许多其他回调)。 http://knockoutjs.com/documentation/template-binding.html

您可能希望将视图包装在模板中,以便访问afterRender回调。

事实上,knockout foreach绑定在内部使用template绑定来支持这些回调。

答案 1 :(得分:1)

您需要explicitly subscribe to the observable

myViewModel.theBoolean.subscribe(function(newValue) {
    if(newValue){ // (Or `newValue === true`, to check if it's not just truthy)
        // The boolean changed to `true`! Do something here.
    }
});
相关问题