stampit-org / stampit

OOP is better with stamps: Composable object factories.
https://stampit.js.org
MIT License
3.02k stars 103 forks source link

'Use metadata in static functions' sample code throws an error #329

Closed pendenaor closed 6 years ago

pendenaor commented 6 years ago

Hi,

I can't make this sample code (from https://github.com/stampit-org/stampit/blob/master/docs/API.md#examples-2) work. it throws an error TypeError: Cannot read property 'addFactorSetter' of undefined at Object.stampit.statics.init:13:35

import stampit from '@stamp/it'

const stamp = stampit()
.statics({
  allowFactorSetter(allow) {
    return this.conf({addFactorSetter: !!allow})
  }
})
.init((opts, {instance, stamp}) => {
  let factor = opts.factor || 1;
  instance.getFactor = () => factor;

  if (stamp.compose.configuration.addFactorSetter) {
    instance.setFactor = f => factor = f;    
  }
});

console.log(stamp().setFactor); // undefined
const stamp2 = stamp.allowFactorSetter(true); 
console.log(stamp2().setFactor(5).getFactor()); // 5

NB: great work, great ideas 👍 But i'm eager to view more detailed examples

koresar commented 6 years ago

Oh, my. Thank you for reporting the issue. I have just fixed the example.

The compose.configuration object can be undefined sometimes if there was no configuration applied to this stamp. So, instead of this:

if (stamp.compose.configuration.addFactorSetter) {

there should have been

if (stamp.compose.configuration && stamp.compose.configuration.addFactorSetter) {