Skip to content

Commit

Permalink
fix(core): use bind of the cloned object for enumerable getter (#1924)
Browse files Browse the repository at this point in the history
fix #1923
  • Loading branch information
aitboudad committed Nov 13, 2019
1 parent 3ae0e8a commit 927151b
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 8 deletions.
9 changes: 5 additions & 4 deletions src/core/json-schema/src/formly-json-schema.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -182,20 +182,21 @@ export class FormlyJsonschema {

// TODO: remove isEnum check once adding an option to skip extension
if (!this.isEnum(schema)) {
const _this = this;
Object.defineProperty(field, 'fieldArray', {
get: () => {
get: function() {
if (!Array.isArray(schema.items)) {
// When items is a single schema, the additionalItems keyword is meaningless, and it should not be used.
return this._toFieldConfig(<JSONSchema7> schema.items, options);
return _this._toFieldConfig(<JSONSchema7> schema.items, options);
}

const length = field.fieldGroup ? field.fieldGroup.length : 0;
const length = this.fieldGroup ? this.fieldGroup.length : 0;
const itemSchema = schema.items[length]
? schema.items[length]
: schema.additionalItems;

return itemSchema
? this._toFieldConfig(<JSONSchema7> itemSchema, options)
? _this._toFieldConfig(<JSONSchema7> itemSchema, options)
: {};
},
enumerable: true,
Expand Down
9 changes: 9 additions & 0 deletions src/core/src/lib/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,4 +196,13 @@ describe('clone', () => {
expect(propDescriptor.get).toBeDefined();
expect(propDescriptor.enumerable).toBeTruthy();
});

it('should use bind of the cloned object', () => {
const d = {};
Object.defineProperty(d, 'a', { get: function() { return this.name; }, enumerable: true });
const value = clone(d);
value.name = 'foo';

expect(value.a).toEqual('foo');
});
});
7 changes: 3 additions & 4 deletions src/core/src/lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,10 +132,9 @@ export function clone(value: any): any {
// need to make a deep copy so we dont use Object.assign
// also Object.assign wont copy property descriptor exactly
return Object.keys(value).reduce((newVal, prop) => {
const propDescriptor = Object.getOwnPropertyDescriptor(value, prop);

if (propDescriptor.get) {
Object.defineProperty(newVal, prop, { ...propDescriptor, get: () => clone(value[prop]) });
const propDesc = Object.getOwnPropertyDescriptor(value, prop);
if (propDesc.get) {
Object.defineProperty(newVal, prop, propDesc);
} else {
newVal[prop] = clone(value[prop]);
}
Expand Down

0 comments on commit 927151b

Please sign in to comment.