mirror of
https://github.com/NativeScript/NativeScript.git
synced 2025-11-05 13:26:48 +08:00
Fixed creating Observable object from nested JSON object.
This commit is contained in:
11
tns-core-modules/data/observable/observable.d.ts
vendored
11
tns-core-modules/data/observable/observable.d.ts
vendored
@@ -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);
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user