9

是否可以手动将计算出的 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);
     }
   })    
}

是否可以使用映射插件在视图模型上生成订单数组,并且还可以在订单数组中插入计算出的 observable “FullName”?

4

2 回答 2

12

在考虑了文档之后,我成功地将其应用于我的示例,如本 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);
于 2013-02-28T20:31:27.643 回答
4

根据文档,您可以:

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);
于 2013-02-28T15:55:05.633 回答