I have knockout a component that I need to render and append several instances of after the page loads but keep getting errors every way I try.
Method that loads 1st component
rendertoolbar: function (toolbar) {
ko.components.get('jq.ko-custom-component', (gridState) => {
let firstComponent = gridState.createViewModel("DefaultT");
firstComponent.doSomeStuff = function () {...};
$(toolbar).append(gridState.template);
ko.applyBindingsToDescendants(firstComponent, toolbar[0]);
})
2nd component loading...
rendertoolbar: function (toolbar) {
ko.components.get('jq.ko-custom-component', (gridState) => {
let secondComponent = gridState.createViewModel("DefaultT");
secondComponent.doSomeOtherStuff = function () {...};
$(toolbar).append(gridState.template);
ko.applyBindingsToDescendants(secondComponent, toolbar[0]);
})
Registering the component
ko.components.register('jq.ko-custom-component', { require: "jq.ko-custom-component" });
Component code:
define('jq.ko-custom-component',
['require',
'module',
'exports',
'text!jq.ko-custom-component.html'],
function (require, module, exports, template) {
var viewModel = function (param) { var stuff = ko.observable(param) }
return {
viewModel: {
createViewModel: (params, componentInfo) => {
return new viewModel(params) }
}, template: template }; });
The main error I keep coming back to is: You cannot apply bindings multiple times to the same element. I tried making a clone of the template or making a small change to it during the creation but that doesn't change the error. I can however change $(toolbar).append(gridState.template); to $(toolbar).append("<jq.ko-custom-component></jq.ko-custom-component>"); but this calls my viewModel twice and doesn't bind the correct instance. Is there another way to do this either with knockout or requirejs?