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

问题描述

使用以下代码,输入#p_in将随着输入#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>

Knockout在内部使用

推荐答案

ko.cleanNode来清理它创建的与元素相关的数据/计算.它不会删除绑定添加的任何事件处理程序,也不会了解绑定是否对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()清除绑定吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 00:28