Skip to content

Commit

Permalink
refactor: make computed property wrapping more clear
Browse files Browse the repository at this point in the history
It wasn't previously clear that the `wrapComputedProperty` behavior is
only invoked for computed properties. This code functions the same, but
makes it easier to see that the computed property wrapping is only
sometimes performed
  • Loading branch information
alexlafroscia committed Feb 21, 2019
1 parent 2943451 commit c670ce8
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 25 deletions.
9 changes: 7 additions & 2 deletions addon/-private/extensions/with-validation.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import Ember from 'ember';

import wrapComputedProperty from '../wrap-computed-property';
import {
isComputedProperty,
wrapComputedProperty
} from '../wrap-computed-property';
import { getValidationsFor } from '../validations-for';

const HAS_VALIDATION = new WeakSet();
Expand Down Expand Up @@ -31,7 +34,9 @@ export function withExtension(klass) {
for (let key in validations) {
const validation = validations[key];

wrapComputedProperty(constructor, this, meta, validation, key);
if (isComputedProperty(meta, key)) {
wrapComputedProperty(constructor, this, meta, validation, key);
}

validation.run(constructor, key, this[key], 'init');
}
Expand Down
49 changes: 26 additions & 23 deletions addon/-private/wrap-computed-property.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,34 +44,37 @@ class ComputedValidatedProperty {
}
}

export default function wrapComputedProperty(
export function isComputedProperty(meta, key) {
const possibleDesc = meta.peekDescriptors(key);

return possibleDesc && possibleDesc.isDescriptor;
}

export function wrapComputedProperty(
klass,
instance,
meta,
typeValidators,
key
) {
const possibleDesc = meta.peekDescriptors(key);
const desc = meta.peekDescriptors(key);

// Handle the argument being overwritten by a computed property
if (possibleDesc && possibleDesc.isDescriptor) {
let originalValue = possibleDesc.get(instance, key);

let validatedProperty = new ComputedValidatedProperty(
possibleDesc,
klass,
originalValue,
typeValidators
);

Object.defineProperty(instance, key, {
configurable: true,
enumerable: true,
get() {
return validatedProperty.get(instance, key);
}
});

meta.writeDescriptors(key, validatedProperty);
}
let originalValue = desc.get(instance, key);

let validatedProperty = new ComputedValidatedProperty(
desc,
klass,
originalValue,
typeValidators
);

Object.defineProperty(instance, key, {
configurable: true,
enumerable: true,
get() {
return validatedProperty.get(instance, key);
}
});

meta.writeDescriptors(key, validatedProperty);
}

0 comments on commit c670ce8

Please sign in to comment.