Knockout mapping ko.mapping.fromJS

时间:2013-06-03 08:47:18

标签: c# asp.net-mvc-4 knockout.js

我有静态方法"objectToMyObject",用于将对象属性转换为MyObject属性objectToMyObject。 我正在尝试将“objectToMyObject”更改为“mapping.fromJS(data)”。但我无法确定。 Hom实现这个问题?

// 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);
             }
         });
 }

1 个答案:

答案 0 :(得分:0)

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

在你的代码&#34; if(!data.succeeded)&#34;语句将始终返回false。如果你想检查&#34;成功&#34;你应该写这个值:&#34; if(!data.succeeded())&#34;

// 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);

我希望它有所帮助