0

这是有效的代码,但使用 knockoutjs 映射插件可能会更好:

我的实体 (e) 上有 5 个域属性,我想用视图模型将实体属性转换为可观察对象。然后我想为每个视图模型添加另一个第 6 个属性,即 isSelected 属性。所有这些都与映射插件有关。

function activate(){
    var schoolyearModels = dataservice.getSchoolyears();
    var schoolyearViewModels = [];
    for (var i = 0; i < schoolyearModels.length; i++){
        var e = schoolyearModels[i];
        var schoolyearViewModel = new SchoolyearViewModel(e.schoolyearId, 
                                            e.schoolyearName, e.from, e.to, 
                                            e.lastEdited, self.Selected);
        schoolyearViewModels.push(schoolyearViewModel);
    }
    return schoolyears(schoolyearViewModels);
}

创建视图模型:

function SchoolyearViewModel(id, schoolyearName, from, to, lastEdited, selected){
    var me = this;
    me.schoolyearId = id;
    me.schoolyearName = ko.observable(schoolyearName);
    me.from = ko.observable(from);
    me.to = ko.observable(to);
    me.lastEdited = ko.observable(lastEdited);
    me.isSelected = ko.computed(function (){
        return selected() === me;
    });
}

来自服务器的数据是 JSON。

我尝试过的早期失败了,因为我从映射插件获得的视图模型没有意义/它不包含它应该包含的属性......

假 JSON 服务器数据:

var s1 = { schoolyearId: 1, schoolyearName: 'Schoolyear 1', 
          from: new Date(), to: new Date(), lastEdited: new Date() };
var s2 = { schoolyearId: 2, schoolyearName: 'Schoolyear 2', 
          from: new Date(), to: new Date(), lastEdited: new Date() };
var s3 = { schoolyearId: 3, schoolyearName: 'Schoolyear 3', 
          from: new Date(), to: new Date(), lastEdited: new Date() };
var s4 = { schoolyearId: 4, schoolyearName: 'Schoolyear 4', 
          from: new Date(), to: new Date(), lastEdited: new Date() };
var s5 = { schoolyearId: 5, schoolyearName: 'Schoolyear 5', 
          from: new Date(), to: new Date(), lastEdited: new Date() };
var s6 = { schoolyearId: 6, schoolyearName: 'Schoolyear 6', 
          from: new Date(), to: new Date(), lastEdited: new Date() };
var s7 = { schoolyearId: 7, schoolyearName: 'Schoolyear 7', 
          from: new Date(), to: new Date(), lastEdited: new Date() };
var s8 = { schoolyearId: 8, schoolyearName: 'Schoolyear 8', 
          from: new Date(), to: new Date(), lastEdited: new Date() };
var s9 = { schoolyearId: 9, schoolyearName: 'Schoolyear 9', 
          from: new Date(), to: new Date(), lastEdited: new Date() };

 var schoolyears = [s1, s2, s3, s4, s5, s6, s7, s8, s9];
 var jsondata = JSON.stringify(schoolyears );
 var viewModelData = ko.mapping.fromJSON(jsondata);

当我现在查看 viewModelData 时,我希望它有 5 个可观察的属性,但它们不存在?

如何正确映射我的 JSON 数据?

4

0 回答 0