javascript - 从外部文件应用绑定
问题描述
我有我希望我的淘汰赛坐在其中的外部文件,代码如下:
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 事件上调用的,所以它不能从数组中获取值吗?我认为这与范围有关,但我无法理解,我敢肯定有非常简单的解释
解决方案
为了使绑定起作用,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>
推荐阅读
- wordpress - 如何在 wordpress 中自定义帖子元?
- reactjs - “错误:您必须将组件传递给连接返回的函数。而不是收到未定义的。”
- python - PYTHON - 启用元素的 StaleElementReferenceException
- python - 将输出转换为 .csv 文件
- python - 使用 padding=0 或 1 的 Pythorch 版本的 Conv2D 的 tensorflow 2.x 中的等价物是什么?
- javascript - Addeventlistener 之间的间隔不一致
- nosql - Oracle NoSQL 数据库云服务中有哪些不同的表状态和生命周期?
- join - MySQL 根据另一个表中的数据查询“UPDATE”
- qt - 设置了 QSortFilterProxyModel 的 QTableView,基于 QSqlQueryModel 在数据库中的数据更改时不会更新
- azure-devops - Azure DevOps 安全扫描作为构建和拉取请求的一部分,仅针对增量更改