CANJS3组件的多个实例

时间:2017-06-23 09:48:39

标签: javascript web canjs canjs-component

使用CanJS(3),我试图插入两次相同的组件,但行为不同。 '父'stache看起来像:

<div class="container-fluid contents">
  <...>
     <my-component someParameters="value1"></my-component>
  </...>
  <...>
      <my-component someParameters="value2"></my-component>
  </...>
</div>

感谢to-child绑定,参数进入子viewModel,这是一个简单的DefineMap。

子组件很简单:

export default Component.extend({
  tag: 'my-component',
  viewModel: myviewmodel (a DefinedMap, with a can-connect attribute, and some others attributes),
  view: view (some stache file),
  events: {
    'inserted': function(el) {
      console.log('inserted my-component...');
    },
  }
});

到目前为止一切顺利,我实现了在同一个窗口上同时显示自定义参数,它显示了差异。

但后来出现了麻烦。 两个子组件都有一个连接(在viewmodel中),然后我希望连接到同一个IP,但订阅另一个通道。

看起来CanJS并没有在事实中实现两个区别的viewmodel,所以我最终得到了我的can-connect对象的相同实例,这使得这项工作变得不可能......

如果有人知道如何在同一个pagem上有两个组件但有两个不同的范围,我会很高兴看到它。

编辑: 真正的问题是“模型”的非单一性(即viewmodel.connect对象)

1 个答案:

答案 0 :(得分:2)

解决方案:

can-connect对象必须在闭包中:

var behaviors = function() {return connect([
    someBehavior,
    anotherBehavior
  ],
  {
    url: {
      getListData: "GET myURL"
    }
  })
};

DefineMap必须像:

var MyMap = DefineMap.extend({
  connection: {value: behaviors},
  parameters: ...
}

一些有趣的阅读: value attribute doc

相关问题