在使用ko.mapping插件生成的observableArray中插入knockout computed observable

时间:2013-02-28 15:52:06

标签: knockout.js knockout-mapping-plugin

是否可以手动将计算的observable插入到使用映射插件生成的数组中?这是一个不使用映射插件的示例,但我想知道它是否可以使用它。

假设我有来自服务器的JSON数据:

[{
    "OrderID":1,
    "FirstName":"Bill",
    "LastName":"Smith",
},{
    "OrderID":2,
    "FirstName":"Jeff",
    "LastName":"Evans",
}
{
    "OrderID":3,
    "FirstName":"Dan",
    "LastName":"Johnson",
}]

在我看来,我有一个Order类和一个视图模型:

function Order(order) {
  var self = this;
  self.OrderID = ko.observable(order.OrderID);
  self.FirstName = ko.observable(order.FirstName);
  self.LastName = ko.observable(order.LastName);

  /*This is what I want to insert after the mapping plugin 
  generates "orders on the ViewModel*/
  self.FullName = ko.computed(function () {
      return self.FirstName() + ' ' + self.LastName();
  });

}

function ViewModel() {
  var self = this;
  self.orders = ko.observableArray([])

//Get orders
  $.ajax({
    url: '@Url.Action("orders")',
    type: "post",
    success: function (data) {
        var mappedOrders = $.map(data, function (item) { return new Order(item) });
        self.orders(mappedOrders);
     }
   })    
}

是否可以使用映射插件在视图模型上生成orders数组,并且还能够在orders数组中插入计算的可观察“FullName”?

2 个答案:

答案 0 :(得分:12)

在考虑了文档之后,我成功地将它应用到我的示例中,如this jsFiddle和以下行中所示:

var data = [{
    OrderID: '1',
    FirstName: 'Bob',
    LastName: 'Stevens'
}, {
    OrderID: '2',
    FirstName: 'Jim',
    LastName: 'Johnson'

}];

function order(data) {
    var self = this;
    var model = ko.mapping.fromJS(data, {}, self);
    model.FullName = ko.computed(function () {
        return self.FirstName() + ' ' + self.LastName();
    });
    return model;
}

var mapping = {
    create: function (options) {
        return new order(options.data);
    }
};

function viewModel() {
    var self = this;
    self.orders = ko.mapping.fromJS(data, mapping);
}

var vm = new viewModel();

ko.applyBindings(vm);

答案 1 :(得分:4)

根据documentation

,您可以
var mapping = {
    'children': {
        create: function(options) {
            return new myChildModel(options.data);
        }
    }
}

var myChildModel = function(data) {
    ko.mapping.fromJS(data, {}, this);

    this.nameLength = ko.computed(function() {
        return this.name().length;
    }, this);
}

var viewModel = ko.mapping.fromJS(data, mapping);