0

I have a simple factory returning an array and a function:

function stockCommons() {
        return {
            unitTypes: [
                {
                    code: 'UN',
                    unitTypeIndex: 0
                },
                {
                    code: 'PK',
                    unitTypeIndex: 2
                },
            ],

            unitTypeChanged: function (changedToUnitType) {
                return var activeUnitType = stockCommons.unitTypes.filter(function (obj) {
                    return obj.code == changedToUnitType;
                })[0];
        }
    }

In the function I'm trying to make a reference to the array at stockCommons.unitTypes but it doesn't work. I've tried these solutions but they don't work either.

How can I use the unitTypes array in the function?

Community
  • 1
  • 1
neptune
  • 1,211
  • 2
  • 19
  • 32

2 Answers2

1
function stockCommons() {
        return {
            unitTypes: function() {
                this.stock = [
                {
                    code: 'UN',
                    unitTypeIndex: 0
                },
                {
                    code: 'PK',
                    unitTypeIndex: 2
                },
               ];
               return this.stock;
            },

            unitTypeChanged: function (changedToUnitType) {
                return var activeUnitType = stockCommons.unitTypes.filter(function (obj) {
                    return obj.code == changedToUnitType;
                })[0];
        }
    }
Raj A
  • 141
  • 1
  • 6
1

Simple solution would be to define unitTypes as private variable and refer it.

function stockCommons() {
    var unitTypes = [{
            code: 'UN',
            unitTypeIndex: 0
        }, {
            code: 'PK',
            unitTypeIndex: 2
        },
    ];

    return {
        unitTypes: unitTypes,

        unitTypeChanged: function (changedToUnitType) {
            var activeUnitType = unitTypes.filter(function (obj) {
                    return obj.code == changedToUnitType;
                })[0];
            return activeUnitType;
        }
    }
}
Satpal
  • 132,252
  • 13
  • 159
  • 168