从外部文件应用绑定

apply bindings from external file

我有我的外部文件,我希望我的淘汰赛坐在里面,代码如下:

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());

然后在名为 search.cshtml 的 MVC 视图页面上,我这样调用上面的内容:

<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(){return counties }" 消息:未定义县

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

要使绑定生效,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()

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

或者,

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

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