使用ko.mapping使knockout observablearray项目可观察

时间:2015-03-10 14:51:31

标签: knockout.js knockout-mapping-plugin

我有这个型号:

var child = function(c){
    var self = this;
    self.id = ko.observable(c.id);
    self.first_name = ko.observable(c.first_name);
    self.last_name = ko.observable(c.last_name);
    self.gender_id = ko.observable(c.gender_id);
    self.birthday= ko.observable(c.birthday);
    self.family_id = ko.observable(c.family_id);
}

我有一个像这样定义的viewmodel:

var childrenViewModel = function(initialData){
    var self = this;
    //
    self.children = ko.observableArray(initialData);
    //
    self.removeChild = function(){};
};

我以这种方式获取最初的数据:

$.ajax({
    type: 'GET',
    url: getChildrenListUrl,
    contentType: 'application/json'
})
    .done(function (data) {
        vmChildren =new childrenViewModel(JSON.parse(data));
        ko.applyBindings(vmChildren,document.getElementById('portlet-children'));
        Metronic.unblockUI('#portlet-children');
    });

我现在想要通过使用映射插件使子节点observablearray,observables自己的内容,我这样做有困难......

1 个答案:

答案 0 :(得分:1)

为什么需要ko.mapping,您是否只想将initialData映射为child的实例?

self.children = ko.observableArray(initialData.map(function(e){ 
                                         return new child(e);
                                   }));

请参阅Array.map