Skip to content

Commit f83256b

Browse files
committed
feat(animation): Implement serializing animation to object and json
1 parent 2c31f87 commit f83256b

1 file changed

Lines changed: 59 additions & 0 deletions

File tree

src/Animation.js

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,4 +183,63 @@ export default class Animation extends EventEmitter {
183183

184184
return new Promise(tick);
185185
}
186+
187+
/**
188+
* Serializes animation to the object representation.
189+
*
190+
* @returns {Object}
191+
*/
192+
toObject() {
193+
return {
194+
type: this.constructor.name,
195+
options: {
196+
duration: this.get('duration'),
197+
easing: this.get('easing')
198+
}
199+
}
200+
}
201+
202+
/**
203+
* Serializes animation to the JSON representation.
204+
*
205+
* @returns {JSON}
206+
*/
207+
toJSON() {
208+
return JSON.stringify(this.toObject());
209+
}
210+
211+
/**
212+
* Static wrapper around new Animation().
213+
*
214+
* @param args
215+
* @returns {Animation}
216+
*/
217+
static create(...args) {
218+
return new this(...args);
219+
}
220+
221+
/**
222+
* Creates animation instance from the Object representation.
223+
*
224+
* @static
225+
* @param {Object} obj Object from {@link toObject} method
226+
* @returns {Animation}
227+
*/
228+
static fromObject(obj) {
229+
if (!obj.type || !obj.options) throw new Error(`It looks like the object is not a representation of the Animation`);
230+
if (obj.type !== this.name) throw new Error(`${obj.type} is not an object representation of the ${this.name}`);
231+
232+
return this.create(obj.options);
233+
}
234+
235+
/**
236+
* Creates animation instance from the JSON representation.
237+
*
238+
* @static
239+
* @param {JSON} json
240+
* @returns {Animation}
241+
*/
242+
static fromJSON(json) {
243+
return this.fromObject(JSON.parse(json));
244+
}
186245
}

0 commit comments

Comments
 (0)