Knockout从AJAX调用加载JSON

时间:2015-01-20 15:00:40

标签: ajax wordpress knockout.js filter pagination

我目前正在使用寻呼机和过滤器创建项目列表。 我使用的基础是:http://jsfiddle.net/JTimperley/pyCTN/13/

但我需要从AJAX加载数据,响应是JSON。

收集创作数据的模型:

function CustomerPageModel(data)
{
  if (!data)
  {
    data = {};
  }

  var self = this;
  self.customers = ExtractModels(self, data.customers, CustomerModel);

  var filters = [
    {
      Type: "text",
      Name: "Name",
      Value: ko.observable(""),
      RecordValue: function(record) { return record.name; }
    },
    {
      Type: "select",
      Name: "Status",
      Options: [
        GetOption("All", "All", null),
        GetOption("None", "None", "None"),
        GetOption("New", "New", "New"),
        GetOption("Recently Modified", "Recently Modified", "Recently Modified")
      ],
      CurrentOption: ko.observable(),
      RecordValue: function(record) { return record.status; }
    }
  ];
  var sortOptions = [
    {
      Name: "ID",
      Value: "ID",
      Sort: function(left, right) { return left.id < right.id; }
    },
    {
      Name: "Name",
      Value: "Name",
      Sort: function(left, right) { return CompareCaseInsensitive(left.name, right.name); }
    },
    {
      Name: "Status",
      Value: "Status",
      Sort: function(left, right) { return CompareCaseInsensitive(left.status, right.status); }
    }
  ];
  self.filter = new FilterModel(filters, self.customers);
  self.sorter = new SorterModel(sortOptions, self.filter.filteredRecords);
  self.pager = new PagerModel(self.sorter.orderedRecords);
}

如果我只是回显events的json值,那么绑定效果很好 但是,当我调用我的AJAX函数并添加新数据时,模型将不会更新。

var data = {
  action: 'load_data'
};
jQuery.post(ajaxurl, data, function(response) {
  var json = JSON.parse(response);
  var models = ExtractModels(_customerPageModel, json, CustomerModel);
  _customerPageModel.customers = models;
});

1 个答案:

答案 0 :(得分:1)

问题是您替换 _customerPageModel.customers变量。

Knockout数据绑定通过使用一些特殊属性 - observablesobservableArray来实现。

您需要绑定到DOM的任何内容都必须是可观察的。

因此,您可能应该将customers转换为observableArray,并在获得新数据时将其推送到它。例如:

function CustomerPageModel(data)
{
  (...)    
  var self = this;
  self.customers = ko.observableArray(ExtractModels(self, data.customers, CustomerModel));
  (...)
}

接收数据时:

var data = {
  action: 'load_data'
};
jQuery.post(ajaxurl, data, function(response) {
  var json = JSON.parse(response);
  var models = ExtractModels(_customerPageModel, json, CustomerModel);
  _customerPageModel.customers.push.apply(_customerPageModel.customers, models);
});

查看observableArray文档:http://knockoutjs.com/documentation/observableArrays.html

请注意,我使用push方法将所有新数据添加到数组的末尾。您可能希望完全覆盖该阵列。如果是这样,那就更简单了:

_customerPageModel.customers(models);

通过这种方式,您的customers数组将替换为新的models数组。