【问题标题】:Make knockout observablearray items observable with ko.mapping使用 ko.mapping 使淘汰 observablearray 项目可观察
【发布时间】:2015-05-12 01:52:22
【问题描述】:

我有这个模型:

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);
}

我有一个这样定义的视图模型:

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 的内容,可观察自己,但我在这样做时遇到了困难......

【问题讨论】:

    标签: knockout.js knockout-mapping-plugin


    【解决方案1】:

    你为什么需要ko.mapping,难道你不想将initialData映射为child的实例吗?

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

    Array.map

    【讨论】:

    • 我想我缺乏标准的 javascript 知识阻止了我首先找到这个,是吗?我认为使用映射是解决这个问题的唯一方法..谢谢
    • @e4rthdog - 你的编辑被拒绝了 - 但它是 100% 正确的,所以我把它放进去了。我的错,对不起。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-05-18
    • 2014-11-05
    • 2012-09-08
    • 2012-07-07
    • 2015-01-25
    • 2012-09-19
    相关资源
    最近更新 更多