将实体映射到视图模型,并使用knockout映射插件向其添加特定的observable

时间:2013-05-06 17:51:43

标签: knockout.js knockout-mapping-plugin

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

我的实体(e)上有5个域属性,我想用viewmodel包装,将实体属性转换为observables。然后我想为每个viewmodel添加另一个第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);
}

创建ViewModel:

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数据?

0 个答案:

没有答案