如何在jqxGrid中同时映射和观察?

时间:2013-07-19 12:05:01

标签: javascript jquery knockout.js jqxgrid jqxwidgets

我将jqxGrid与KnockoutJS一起使用。我将网格绑定到一个对象数组。当我使用映射时,网格的值不会刷新。但是,如果我将一个新对象推送到添加到网格中的数组。

<script type="text/javascript">
var viewModel = null;
var initialData = [
  { name: "Well-Travelled Kitten", sales: 352, price: 75.95, Address: { City: "asdf", Street: "asdf"} },
  { name: "Speedy Coyote", sales: 89, price: 190.00, Address: { City: "asdf", Street: "asdf"} },
  { name: "Furious Lizard", sales: 152, price: 25.00, Address: { City: "asdf", Street: "asdf"} },
  { name: "Indifferent Monkey", sales: 1, price: 99.95, Address: { City: "asdf", Street: "asdf"} },
  { name: "Brooding Dragon", sales: 0, price: 6350, Address: { City: "asdf", Street: "asdf"} },
  { name: "Ingenious Tadpole", sales: 39450, price: 0.35, Address: { City: "asdf", Street: "asdf"} },
  { name: "Optimistic Snail", sales: 420, price: 1.50, Address: { City: "asdf", Street: "asdf"} }
];
$(document).ready(function () {
  var GridModel = function (items) {
    this.items = ko.observableArray(items);
    this.addItem = function () {
      this.items.push({ name: "New item", sales: Math.round(Math.random() * 100), price: Math.round(Math.random() * 100),Address: { City: "asdf", Street: "asdf"} });
      $("#jqxgrid").jqxGrid('updatebounddata');
    };
    this.removeItem = function () {
      this.items.pop();
      $("#jqxgrid").jqxGrid('updatebounddata');
    };
    this.source = {
      datafields: [
        { name: 'name' },
      ],
      localdata: initialData
    }
  };
  viewModel = new GridModel(initialData);
  ko.applyBindings(viewModel);
  var dataAdapter = new $.jqx.dataAdapter(viewModel.source,{ autoBind: true});
  dataAdapter.dataBind();
  // create jqxGrid.
  $("#jqxgrid").jqxGrid({
    source: dataAdapter,
    autoheight: true,
    pageable: true,
    editable: true,
    columns: [
      { text: 'Name', dataField: 'name', width: 200 },
      { text: 'Sales', dataField: 'sales', width: 200, cellsalign: 'right' },
      { text: 'Price', dataField: 'price', width: 200, cellsformat: 'c2', cellsalign: 'right' },
    ]
  });
});
</script>

如果我不写

datafields: [
 { name: 'name' },
],

进入源头,然后一切都很好。

我如何能够同时映射并保持观察效果?

1 个答案:

答案 0 :(得分:0)

数组项应该是ko.observable本身。试试这样的addItem函数:

this.addItem = function () {
      this.items.push(
            ko.observable({ name: "New item", sales: Math.round(Math.random() * 100), price: Math.round(Math.random() * 100),Address: { City: "asdf", Street: "asdf"} })
      );
      $("#jqxgrid").jqxGrid('updatebounddata');
    };