可以使用 cleanNode() 来清理绑定吗? [英] Can cleanNode() be used to clean binding?

查看:22
本文介绍了可以使用 cleanNode() 来清理绑定吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用下面的代码,input#p_in 将随着 input#s_in 的变化而更新.但是我使用了cleanNode(sec).任何人都可以帮助理解为什么没有清除绑定.

With below code, input#p_in will be updated with the change of input#s_in. But I have used cleanNode(sec). Could anyone help understand why the binding is not cleared.

    <input id="p_in" data-bind="value: name"></input>
    <input id="s_in" data-bind="value: name"></input>
    <input id="cb" type="checkbox">same</input>

    <script type="text/javascript">
        function AddrDataSet (name) {
            this.name = ko.observable(name);
        };

        var primary_set = new AddrDataSet('p');
        var sec_set = new AddrDataSet('s');
        var pri = $('#p_in')[0];
        var sec = $('#s_in')[0];

        ko.applyBindings(primary_set, pri);
        ko.applyBindings(sec_set, sec);

        ko.cleanNode(sec); // clean it
        ko.applyBindings(primary_set, sec); // bind it to primary_set
        ko.cleanNode(sec); // clean it again

    </script>

推荐答案

ko.cleanNode 由 Knockout 在内部使用,以清理它创建的与元素相关的数据/计算.它不会删除任何由绑定添加的事件处理程序,也不会了解绑定是否对 DOM 进行了更改.这肯定会导致一些问题,例如在随后再次绑定元素时将多个处理程序附加到元素上.

ko.cleanNode is used internally by Knockout to clean up data/computeds that it created related to the element. It does not remove any event handlers added by bindings or necessarily understand if a binding made changes to the DOM. This can definitely cause problems like having multiple handlers attached to an element when it is subsequently bound again.

所以,我不推荐使用这种模式.更好的模式是在一个部分周围使用 withtemplate 绑定,并允许它使用新绑定重新呈现.

So, I would not recommend using this pattern. A better pattern is to use with or the template binding around a section and allow it to be re-rendered with the new bindings.

这篇关于可以使用 cleanNode() 来清理绑定吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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