首页 > 解决方案 > 从外部文件应用绑定

问题描述

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

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>

我得到的错误是:

Uncaught ReferenceError: Unable to process binding "foreach: function(){return counties }" 消息:counties is not defined

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

标签: javascriptdata-bindingknockout.js

解决方案


为了使绑定起作用,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对象。因此,您需要self在外部保留对 viewModel 的引用并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>

推荐阅读