简体   繁体   English

Knockoutjs 中的自定义组件绑定

[英]custom component binding in knockoutjs

I am trying to load custom components using knockoutjs.我正在尝试使用knockoutjs 加载自定义组件。

Here is my HTML :这是我的 HTML :

<div id="mainDiv"></div>

JS: JS:

$("#mainDiv").append("<my-component-name></my-component-name>");

This appends <my-component-name></my-component-name> after div but does not bind my component to html.这会在 div 之后附加<my-component-name></my-component-name>但不会将我的组件绑定到 html。

If I use ko.applyBindings();如果我使用ko.applyBindings(); it throws error "Error: You cannot apply bindings multiple times to the same element."它会引发错误"Error: You cannot apply bindings multiple times to the same element."

I am not able to find whats wrong with bindings.我无法找到绑定有什么问题。

The view is updated, but the bindings are not.视图已更新,但绑定未更新。 You need to do ko.applyBindings on any elements inserted in the HTML after the bindings are applied the first time.在第一次应用绑定后,您需要对插入到 HTML 中的任何元素执行ko.applyBindings It's a lousy solution to apply components after applying bindings.在应用绑定后应用组件是一个糟糕的解决方案。 And DON'T mix knockout with jQuery or js DOM manipulation, PLEEEASSE!并且不要将淘汰赛与 jQuery 或 js DOM 操作混用,PLEEEASSE!

Here I got the solution:在这里我得到了解决方案:

var myComp = document.createElement("my-component-name");
$("#mainDiv").append(myComp);
ko.applyBindings({},myComp);

Ko.applyBinding was needed to bind my component in html. Ko.applyBinding 需要在 html 中绑定我的组件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM