从外部文件应用绑定

时间:2019-01-26 23:31:50

标签: javascript data-binding knockout.js

我有我要删除的外部文件,其代码如下:

var ViewModel = function () {
var counties = ko.observableArray([]);

this.getCounties = function () {
    $.ajax({
        url: '/Search/ByCounty',
        type: 'GET',
        success: function (data) {
            if (data && data.length > 0) {
                for (var i = 0; i < data.length; i++) {
                    var obj = data[i];
                    counties.push(obj.CountyName);
                }
            }
        },
        error: function (error) {
            console.log(error);
        }
    });
};
};

ko.applyBindings(new ViewModel());

然后在我的MVC视图页面search.cshtml上,我这样称呼上述内容:

<button type="button" class="btn btn-primary" data-bind="click: getCounties">getCounties</button>

这似乎将所有数据推入数组,然后我想做的下一个方面是循环县,就像这样:

<table>
    <thead>
        <tr><th>Counties</th></tr>
    </thead>
    <tbody data-bind="foreach: counties">
        <tr>
            <td data-bind="text: CountyName"></td>
        </tr>
    </tbody>
</table>

我得到的错误是:

未捕获的ReferenceError:无法处理绑定“ foreach:function(){返回县}” 消息:未定义县

我不明白,在那的click事件上调用了getCounties,所以它不能从数组中获取值吗?我认为这与范围有关,但我无法理解,我敢肯定有一个非常简单的解释

1 个答案:

答案 0 :(得分:1)

为使绑定起作用,countries应该是ko.applyBindings()中使用的对象的属性。当前,您只是在填充一个名为countries的局部变量。将您的代码更改为:

var ViewModel = function() {
  var self = this;

  this.counties = ko.observableArray([]);
  this.getCounties = function() {
    $.ajax({
      url: '/Search/ByCounty',
      type: 'GET',
      success: function(data) {
        if (data && data.length > 0) {
          for (var i = 0; i < data.length; i++) {
            var obj = data[i];
            self.counties.push(obj.CountyName);
          }
        }
      },
      error: function(error) {
        console.log(error);
      }
    });
  };
};

ko.applyBindings(new ViewModel());

在ajax成功回调中,this引用jqXHR对象。因此,您需要在外部保留对viewModel的引用self,并在回调内部使用self.counties.push()

这仍然不会为您显示国家/地区。因为根据您的绑定,剔除会在每个CountyName中寻找countries属性。因此,您需要像这样self.counties.push(obj)推动整个对象。

或者,

如果您希望将countries保留为字符串数组,则可以在循环上下文中使用$data关键字来引用当前的country

<tbody data-bind="foreach: counties">
    <tr>
        <td data-bind="text: $data"></td>
    </tr>
</tbody>
相关问题