首页 > 解决方案 > 页面加载后渲染同一个淘汰组件的多个实例

问题描述

我已经淘汰了一个组件,我需要在页面加载后渲染和附加几个实例,但每次尝试都会出错。

加载第一个组件的方法

  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]);
  })

第二个组件加载...

  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]);
  })

注册组件

ko.components.register('jq.ko-custom-component', { require: "jq.ko-custom-component" });

组件代码:

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 }; });

我不断回到的主要错误是:您不能将绑定多次应用于同一个元素。我尝试在创建过程中克隆模板或对其进行小幅更改,但这并没有改变错误。但是,我可以更改 $(toolbar).append(gridState.template); 到 $(toolbar).append("<jq.ko-custom-component></jq.ko-custom-component>"); 但这会调用我的 viewModel 两次并且没有绑定正确的实例。是否有另一种方法可以通过淘汰赛或 requirejs 做到这一点?

标签: knockout.jsrequirejs

解决方案


推荐阅读