Best practice: getter/setter pattern
Closed this issue · 1 comments
Hi there,
RawModel is fantastic. How would you suggest creating getter/setter functions that need to reference other field values?
For example
public isSurveyComplete: boolean;
public eventDate: Date;
...
this.defineField('isSurveyComplete', {'Boolean'});
this.defineField('eventDate', {
type: 'Date',
get(value) {
if(this.isSurveyComplete) {
return value;
}
else {
return null;
}
},
});
I've read through your documentation and source code. It looks like the 'field' values are 'protected' and therefore not accessible (makes sense).
My work around is to do something like the following:
`
....
this.populate(data);
// append getter/setters after values are populated
Object.defineProperty(this, 'eventDate', {
get: function () {
if (this.isSurveyComplete) {
return this.eventDate;
}
}
});
`
Is there a better way? I'd like to maintain the 'validate' functionality that you've provided.
Thank you!
Hey @bidwej. I'm glad you like it.
Each field can access model's context through the this.owner
field. The owner
is a model that owns the field and thus represents a link between a Model
and a Field
. In your case you would do something like this:
this.defineField('eventDate', {
type: 'Date',
get(v) {
return this.owner.isSurveyComplete ? v : null;
},
});
Using Object.defineProperty
is not advised. Note that you can access all instance methods of the Field
through this
(e.g. this.hasErrors()).