js-data v3 computed properties

node v6.17.1
version: 4.0.0
endpointsharetweet
Setup
const JSData = require('js-data@3.0.0-beta.7') const {Container, Record, version} = JSData const store = new Container() console.log(`Using JSData v${version.full}`)
Variant #1 - Use the Mapper's Schema
store.defineMapper('circle', { schema: { properties: { radius: { type: 'number' }, // Computed property area: { type: 'number', get () { return Math.PI * Math.pow(this.radius, 2) } } } } }) const circle = store.createRecord('circle', { radius: 2.5 }) console.log(`circle.radius: ${circle.radius}`) console.log(`circle.area: ${circle.area}`)
Variant #2 - Modify prototype of Mapper's recordClass
store.defineMapper('user') Object.defineProperties(store.getMapper('user').recordClass.prototype, { // Computed property name: { enumerable: true, get () { return `${this.first} ${this.last}` }, set (value) { const parts = value.split(' ') this.first = parts[0] || '' this.last = parts[1] || '' } } }) const user = store.createRecord('user', { first: 'John', last: 'Anderson' }) console.log(`user.first: ${user.first}`) console.log(`user.last: ${user.last}`) console.log(`user.name: ${user.name}`)
Variant #3 - Provide a custom class (ES2015)
class Rectangle extends Record { // Computed property get area () { return this.width * this.height } } store.defineMapper('rectangle', { recordClass: Rectangle }) const rectangle = store.createRecord('rectangle', { width: 2, height: 4 }) console.log(`rectangle.width: ${rectangle.width}`) console.log(`rectangle.height: ${rectangle.height}`) console.log(`rectangle.area: ${rectangle.area}`)
Loading…

no comments

    sign in to comment