CanJS - correct way to pass a callback from the viewmodel to the stache file

23 views Asked by At

I have an old CanJS component which is renders a React component, and where now I need to pass a callback.

I found a way to pass the callback but I feel it's not the best way because in some cases it seems that the viewmodel reference is not the same and therefore some properties are not updated correctly in some moments.

My CanJS component - viewmodel:

export default DefineMap.extend("StoreVM", {

  pencils: {
    Type: DefineList.extend({
      '#': "number",
      hasStock() {
        return this.every(i => i > 0);
      }
    }),
    default() {
      return [60, 5, 30];
    }
  },

  handleProductStockChange: {
    value() {
      const onStockChange = (amount) => {
        this.pencils[2] = amount;
        this.onPencilsStockChange && this.onPencilsStockChange(this.pencils.hasStock());
      };
      return onStockChange.bind(this);
    }
  }
});

My CanJS component - stache:

<can-import from="pm-gui/components/pencils"/>

<store-pencils onStockChange:from="handleProductStockChange" />

Initially I was trying to implement the callback this way:

handleProductStockChange (amount) => {
  this.pencils[2] = amount;
  this.onPencilsStockChange && this.onPencilsStockChange(this.pencils.hasStock());
},

However the 'this' reference doesn't exist if I do the method this way.

What is the correct way to define the callback in the viewmodel?

I don't find anything helpful in the CanJs documentation about this.

CanJs versions in use:

"can-component": "^5.0.0",
"can-connect": "^4.0.1",
"can-construct": "^3.5.6",
"can-construct-super": "^3.2.1",
"can-control": "^5.0.1",
"can-debug": "^2.0.7",
"can-define": "^2.8.0",
"can-define-backup": "^2.1.2",
"can-deparam": "^1.2.2",
"can-diff": "1.5.0",
"can-dom-data": "^1.0.3",
"can-dom-events": "^1.3.11",
"can-dom-mutate": "^2.0.9",
"can-key": "^1.2.1",
"can-list": "^4.2.3",
"can-log": "^1.0.2",
"can-map": "^4.3.15",
"can-map-define": "^4.4.0",
"can-model": "^4.1.0",
"can-observable-array": "^1.1.4",
"can-observable-object": "^1.1.4",
"can-observation": "^4.2.0",
"can-param": "^1.1.3",
"can-query-logic": "^1.2.2",
"can-queues": "^1.3.2",
"can-react-component": "^3.0.0",
"can-reflect": "^1.18.0",
"can-set-legacy": "^1.0.1",
"can-stache": "^5.1.1",
"can-stache-bindings": "^5.0.5",
"can-stache-converters": "^5.0.0",
"can-stache-element": "^1.2.0",
"can-symbol": "^1.6.5",
"can-type": "^1.1.6",
"can-types": "^1.4.0",
"can-util": "^3.14.0",
"can-view-autorender": "^6.0.0",
"can-view-callbacks": "^5.0.0",
"can-view-model": "^4.0.3",
0

There are 0 answers