2015-10-19 62 views
0

我有一个服务器的数据,如下。添加额外的对象属性来敲除映射

var data = [{ 
 
    'Name': 'David', 
 
    'Class': '2A' 
 
}, { 
 
    'Name': 'Vincent', 
 
    'Class': '2B' 
 
}]

假设我检索数据,并使用ko.mapping.fromJS映射。但是,我想在映射后使数据由另一个属性名称Grade组成。这怎么能实现?这是因为属性等级的值通过另一个Ajax调用来检索,并且应该事先定义。

function MyViewModel() { 
 
    var self = this; 
 
    self.StudentProfile = ko.observableArray([]); 
 
    
 
    self.GetStudentProfile = function() { 
 
    $.ajax({ 
 
     .. 
 
     .. 
 
     success: function(data) { 
 
      ko.mapping.fromJS(data.StudentProfile, {}, self.StudentProfile); 
 
      // data after mapping 
 
      $.each(self.StudentProfile, function (index, value) { 
 
      $.ajax({ 
 
       .. 
 
       .. 
 
       success: function(data) { 
 
        self.StudentProfile()[index].Grade(data); 
 
       } 
 
      }); 
 
      } 
 
     } 
 
    }) 
 
    } 
 
} 
 

 
// data after mapping 
 
var data = [{ 
 
    'Name': 'David', 
 
    'Class': '2A', 
 
    'Grade': '' 
 
}, { 
 
    'Name': 'Vincent', 
 
    'Class': '2B', 
 
    'Grade': '' 
 
}]

+0

你试过self.StudentProfile()[指数] .Grade = ko.observable(数据);而不是self.StudentProfile()[index] .Grade(data); ? –

回答

3

您可以使用

var options = { 
    create: function(options){ 
     options.data.Grade = ko.observable(""); 
     return options.data; 
    } 
} 

ko.mapping.fromJS(data.StudentProfile, options, self.StudentProfile);