props-model
A javascript package providing a model for properties, including change events and derived properties.
Overview
This package provides the PropertyModel
class which can serve as the M in an MVC pattern, or more generally
to track and manage a set of named properties. In addition to get and modify access for the properties, the
model also provides synchronous change event firing and listener creation for the managed properties. It
also allows you to define derived properties whose values are automatically calculated anytime a property
it depends on changes.
Install
With npm:
npm install --save props-model
Demo Usage
const PropModel = require('.')
const EventEmitter = require('events')
class MutableRectangle {
constructor (initialLength, initialWidth) {
const propModel = new PropModel(new EventEmitter())
.defineProp('length', initialLength, isValidDimension)
.defineProp('width', initialWidth, isValidDimension)
.defineDerivedProp('area', ['length', 'width'], (length, width) => length * width)
.defineDerivedProp('perimeter', ['length', 'width'], (length, width) => (2 * length) + (2 * width))
.defineDerivedProp('aspectRatio', ['length', 'width'], (length, width) => length / width)
propModel.installAccessors(this, {
length: 'readwrite',
width: 'readwrite',
area: 'readonly',
perimeter: 'readonly',
aspectRatio: 'readonly'
})
this.toJSON = () => propModel.toJSON()
}
}
function isValidDimension (dim) {
if (typeof dim !== 'number') {
throw new Error('Invalid dimension, must be a number')
}
if (dim < 0) {
throw new Error('Invalid dimension, must be non-negative')
}
}
function main () {
const rect = new MutableRectangle(10, 20)
console.log(JSON.stringify(rect))
rect.setLength(15)
console.log(rect.getLength())
console.log(rect.getArea())
console.log(JSON.stringify(rect))
}
main()