我有像這樣的一個用戶對象:淘汰賽映射響應對象
var userModel = {
Id: ko.observable(),
Email: ko.observable().extend({ email: true, required: true, maxLength: 200 }),
FirstName: ko.observable().extend({ required: true, minLength: 2, maxLength: 200 }),
LastName: ko.observable().extend({ required:true, minLength: 2, maxLength: 200 }),
DefaultLanguage: ko.observable(),
Phone: ko.observable().extend({phoneUS:true}),
AvatarUrl: ko.observable(),
Claims: ko.observableArray()
};
我加載的響應,並希望到對象的響應綁定。響應與模型的格式完全相同:
self.user = userModel;
self.loadData = function (params) {
$.get('/api/user/' + params.id).then(function (data) {
console.log('GET User', data);
self.user.Id(data.Id);
self.user.Email(data.Email);
self.user.FirstName(data.FirstName);
self.user.LastName(data.LastName);
self.user.Phone(data.Phone);
self.user.DefaultLanguage(data.DefaultLanguage);
self.user.AvatarUrl(data.AvatarUrl);
self.user.Claims(data.Claims);
});
};
雖然上面的工作很棒,但它真的很長。有沒有更簡單的方法來綁定對象?
你可以用 'ko.mapping.fromJS()'(http://knockoutjs.com/documentation/plugins-mapping.html) –
嘗試,它並沒有self.user工作是不是功能。 – allencoded
這不起作用? ko.mapping.fromJS(data,{},self.user); –