1

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?

Josh
  • 35
  • 4
  • As the error suggests not applying bindings multiple times. You can try ko.cleanNode(element); method and again apply bindings to every element for further details you can refer this link: https://stackoverflow.com/questions/10048485/how-to-clear-remove-observable-bindings-in-knockout-js#:~:text=If%20you%20would%20like%20to,with%20binding%22)%20will%20disappear. – mukhtar alam Feb 23 '21 at 11:04

0 Answers0