KnockoutJS 2.3: 'custom binding' + 'ko.applyBindings to partial view' throws error

混江龙づ霸主 提交于 2020-01-14 03:13:08

问题


I've got some code that uses knockout.js, a custom binding and a calls applyBindings() to a partial view. jsfiddle with ko 2.2.1

    var handle = slider.slider().find(".ui-slider-handle").first();
    $(handle).attr("data-bind", "tooltip: viewModel.value");
    ko.applyBindings(viewModel.value, $(handle)[0]);

Now, with ko version 2.3, I get the error "You cannot apply bindings multiple times to the same element." jsfiddle with ko 2.3

I've probably always had this problem but previous versions of knockout wouldn't throw an exception. I've added a call to cleanNode() just before the partial applyBindings but that doesn't help.

    var handle = slider.slider().find(".ui-slider-handle").first();
    $(handle).attr("data-bind", "tooltip: viewModel.value");
    ko.cleanNode($(handle)[0]);
    ko.applyBindings(viewModel.value, $(handle)[0]);

Interestingly, binding works with the dynamic tooltip but not with a static field, so I think the error is thrown after applying the partial view binding. I've tried to follow the chain of calls that occurs after the global ko.applyBindings() but it's deeply nested, and got lost. All I know is that the custom binding is initialized then, after ko.applyBindings(). I don't know whether there's a way to add custom handlers later on, perhaps that could help. I hope that's clear enough.

Linked question.


回答1:


Of course!! I don't even need to call applyBindings() to the partial view, adding the right attribute is enough:

var handle = slider.slider().find(".ui-slider-handle").first();
$(handle).attr("data-bind", "tooltip: viewModel.value");
/*ko.applyBindings(viewModel.value, $(handle)[0]);*/


来源:https://stackoverflow.com/questions/18883556/knockoutjs-2-3-custom-binding-ko-applybindings-to-partial-view-throws-err

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!