A computed value determines an attribute’s value from an expression instead of storing a fixed initial value. The attribute explicitly selects the value kind: initially or computed as. This distinction lets the runtime represent stored fields and derived values without ambiguity. section 11.1.1
Implementing computed values requires coordinated changes across the DSL, runtime generation, and expression handling:
- Represent the attribute with a value expression and a value kind, replacing the separate initial value property. section 11.1.1
- Detect computed attributes with a query such as isComputedFromExpression. section 11.4
- Generate a getter for computed attributes and an initializer for ordinary attributes. section 11.4
- Recursively translate expression nodes, including binary operations, into generated JavaScript. section 11.4
Rental price after discount
A rental price after discount can be declared as a computed attribute. Code generation emits a getter such as get rentalPriceAfterDiscount(), whose return expression evaluates the referenced price and discount. A binary operator of is translated into multiplication by 0.01 so a percentage discount is applied correctly. section 11.4
Listing 11.16 The classField template function
const classField = (attribute) => {
const { settings } = attribute
const value = settings["value"]
const fieldName = camelCase(settings["name"])
if (isComputedFromExpression(attribute)) { #1
return [ #2
`get ${fieldName}() {`,
` return ${expressionFor(value)}`,
`}`
]
}
return initializationFor(attribute) #3
}
Inspect the classField template to see how computed attributes become getters while initially valued attributes retain initializer generation. section 11.4
