0

我有"objectToMyObject"将对象属性转换为MyObject属性 的静态方法objectToMyObject。我正在尝试将“ objectToMyObject”更改为“ mapping.fromJS(data)”。但我不能这样决定。主页实现这个问题?

// My get method:
 getMyObject(url: string, params: any, onSuccess: () = > {}, onError: (message: string) = > {}) {
     this.invokeAjax(url, params, (data) = > {
             if (!data.succeeded) {
                 onError(data.error);
             } else {
                 this.editMyObject(MyObject.objectToMyObject(data));
                 //this.editMyObject(<any>this.editMyObject((<any>ko).mapping.fromJS(data)));
                 onSuccess();
             }
         });
 }



 // My invoke method:
 invokeAjax(url: string, params, callback: (result: any) = > {}) {
     $.ajax({
             url: url,
             type: 'GET',
             data: params,
             dataType: 'json',
             cache: false,
             success: (data) = > {
                 callback(data);
             },
             error: (data) = > {
                 this.succeeded(false);
             }
         });
 }
4

1 回答 1

0

我改变了你的代码。如您所见,它总是使用成功参数调用回调函数。

在您的代码中,“if(!data.succeeded)”语句将始终返回 false。如果你想检查“成功”值,你应该这样写:“if(!data.succeeded())”

// My get method:
 getMyObject(url: string, params: any, onSuccess: () = > {}, onError: (message: string) = > {}) {
     this.invokeAjax(url, params, (data, success) = > {
             if (!success) {
                 onError(data.error);
             } else {
                 ko.mapping.fromJS](vm /*your view model (may be this)*/, {}, data)
                 //this.editMyObject(MyObject.objectToMyObject(data));
                 //this.editMyObject(<any>this.editMyObject((<any>ko).mapping.fromJS(data)));
                 onSuccess();
             }
    });
 }



 // My invoke method:
 invokeAjax(url: string, params, callback: (result: any, success : any) = > {}) {
     $.ajax({
             url: url,
             type: 'GET',
             data: params,
             dataType: 'json',
             cache: false,
             success: (data) = > {
                 callback(data, true);
             },
             error: (data) = > {
                 callback(data, false);
             }
    });
 }

我对你第一个问题的回答

早期,在您的代码中,您通过调用 ko.applyBindings(vm) 将视图模型绑定到视图。现在,当你收到来自 ajax 回调的刷新数据时,你可以调用ko.mapping.fromJS (vm, {}, data);

我希望它有帮助

于 2013-06-03T09:15:16.687 回答