I have hardcoded classes to represent models in my Aurelia application. Here\'s a model \'PostEdit\':
var _postID = Symbol();
var _title = Symbol();
var _te
Give your class a toJSON
method that returns a stringifyable object:
export class PostEdit {
constructor(postEdit) {
this[_postID] = postEdit.postID;
this.title = postEdit.title;
this.text = postEdit.text;
}
get postID() { return this[_postID]; }
get title() { return this[_title]; }
set title(val) { this[_title] = val; }
get text() { return this[_text]; }
set text(val) { this[_text] = val; }
toJSON() {
return {
postId: this.postId,
title: this.title,
text: this.text
};
}
}
JSON.stringify will automatically call that and replace your instance with the result.
Also you might want to add a fromJSON
method to your class that you can use to revive instances during JSON.parse
. It is trivial in your case:
static fromJSON(obj) {
return new this(obj);
}
but you might need something more complicated in other classes.