【发布时间】:2013-12-27 15:09:22
【问题描述】:
我对使用 Knockout 有点陌生,但遇到了问题。我有搜索功能,它返回 JSON 数据并更新填充选择列表的 observableArray。我已经让它在初始加载时加载了一个默认设置,然后您可以搜索关键字文本,它会进行 Web api 调用并更新 observableArray。这一切都有效,但选择列表不会更新。我确定我只是错过了一些简单的东西,但一直无法弄清楚它是什么。我创建了一个小提琴,它重现了我正在做的同样缺乏结果的事情。
这是 HTML:
<button href="#" data-bind="click: updateSearch">Search</button><br/>
<select data-bind="options: customerResults,
optionsText: function(item) {
return item.Name
},
value: selectedCustomer,
optionsCaption: '- Please Select -',
valueUpdate: 'change'" size="15">
</select>
这是 JS:
$(function () {
var custResult = function(Id, Name, Address1, City, State) {
this.Id = Id;
this.Name = Name;
this.Address1 = Address1;
this.City = City;
this.State = State;
};
// Test data for initial binding
var data = [
new custResult(1, "Test1", "123 Fake St", "Springfield", "VT"),
new custResult(2, "Test2", "123 Fake St", "Springfield", "VT"),
new custResult(3, "Test3", "123 Fake St", "Springfield", "VT"),
];
// Test data for rebinding
var data2 = [
new custResult(1, "TestA", "123 Fake St", "Springfield", "VT"),
new custResult(2, "TestB", "123 Fake St", "Springfield", "VT"),
new custResult(3, "TestC", "123 Fake St", "Springfield", "VT"),
new custResult(1, "TestD", "123 Fake St", "Springfield", "VT"),
new custResult(2, "TestE", "123 Fake St", "Springfield", "VT"),
new custResult(3, "TestF", "123 Fake St", "Springfield", "VT"),
];
var viewModel = {
customerResults: ko.observableArray(data),
selectedCustomer: ko.observable(),
updateSearch: function () {
this.customerResults = null;
this.customerResults = data2
alert("item " + this.customerResults.length.toString() + " = " + this.customerResults[this.customerResults.length - 1].Name.toString());
},
nameVisible: ko.observable(true)
};
ko.applyBindings(viewModel);
});
这是小提琴。 http://jsfiddle.net/bsdavey/4M2Rh/
知道我在这里做错了什么吗?
【问题讨论】:
-
我有一个建议,与其尝试将数组交换为可观察的,不如删除并重新填充“数据”,我也是 KO 的新手,据我所知,从数据中删除并重新填充会导致它更新选择列表。你试过了吗?
标签: javascript jquery knockout.js ko.observablearray