Fixed creating Observable object from nested JSON object.

This commit is contained in:
Nedyalko Nikolov
2016-08-12 15:05:42 +03:00
parent a736bc0ae4
commit 3fc706972f
4 changed files with 52 additions and 12 deletions

View File

@@ -70,8 +70,19 @@ declare module "data/observable" {
*/
public static propertyChangeEvent: string;
/**
* Creates an Observable instance and sets its properties according to the supplied JSON object.
*/
public static fromJSON(json: any): Observable;
/**
* Creates an Observable instance and sets its properties according to the supplied JSON object.
* This function will create new Observable for each nested object (expect arrays and functions) from supplied JSON.
*/
public static fromJSONRecursive(json: any): Observable;
/**
* [Deprecated please use static functions fromJSON or fromJSONRecursive instead] Creates an Observable instance and sets its properties according to the supplied JSON object.
*/
constructor(json?: any);

View File

@@ -51,18 +51,37 @@ export class Observable implements definition.Observable {
private _observers = {};
public static fromJSON(json: any): Observable {
let observable = new Observable();
observable.addPropertiesFromJSON(observable, json, false);
return observable;
}
public static fromJSONRecursive(json: any): Observable {
let observable = new Observable();
observable.addPropertiesFromJSON(observable, json, true);
return observable;
}
private addPropertiesFromJSON(observable: Observable, json: any, recursive?: boolean) {
let isRecursive = recursive || false;
observable._map = new Map<string, Object>();
for (var prop in json) {
if (json.hasOwnProperty(prop)) {
if (isRecursive) {
if (!Array.isArray(json[prop]) && typeof json[prop] === 'object' && types.getClass(json[prop]) !== 'ObservableArray') {
json[prop] = Observable.fromJSONRecursive(json[prop]);
}
}
observable._defineNewProperty(prop);
observable.set(prop, json[prop]);
}
}
}
constructor(json?: any) {
if (json) {
this._map = new Map<string, Object>();
for (var prop in json) {
if (json.hasOwnProperty(prop)) {
if (!Array.isArray(json[prop]) && typeof json[prop] === 'object') {
json[prop] = new Observable(json[prop]);
}
this._defineNewProperty(prop);
this.set(prop, json[prop]);
}
}
this.addPropertiesFromJSON(this, json);
}
}