Search code examples
javascriptwebcanjscanjs-component

CANJS3 multiple instances of a component


With CanJS (3), I'm trying to insert twice the same component, but with a different behavior. The 'parent' stache looks like :

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

Thanks to to-child binding, the parameter is getting in the child viewModel, which is a simple DefineMap.

The child component is simple :

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...');
    },
  }
});

So far so good, I achieve to have both on the same window, and while displaying the custom parameters, it shows the difference.

But then came troubles. Both child component has a connection, (in the viewmodel), and I expect then to connect to the same IP, but to subscribe to a different channel.

It looks like CanJS doesn't instanciate two distincts viewmodel in facts, so I end up with the same instance of my can-connect object, which make the work impossible ...

If anyone has an idea of how to have two components on the same pagem but with two different scope, I'll be pleased to read it.

EDIT: The real problem is the non-unicity of the "model" (ie the viewmodel.connect object)


Solution

  • The solution :

    The can-connect object must be in a closure :

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

    And the DefineMap must be like :

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

    Some interesting reading : value attribute doc