我正在使用 knockout js 和 chosen 插件 (https://github.com/harvesthq/chosen) 来尝试制作一个好看的多选。
我已经尝试了多种方法,但无法让多选来处理我正在使用的数据。当我单击多选时,即使选项绑定(bind)包含正确的数据,也不会显示任何值。
HTML:
<select multiple="multiple" data-bind="options: allCustomers,
selectedOptions: event().customers, optionsText: 'name',
optionsValue: 'id', chosen: true " ></select>
View 模型的简化版本:
function Event()
{
this.customers = ko.observableArray();
};
//for chosen plugin
ko.bindingHandlers.chosen = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
$(element).chosen();
}
}
function ViewModel()
{
this.event = ko.observable(new Event());
this.allCustomers = ko.observableArray();
};
var viewModel = new ViewModel();
$.getJSON("/get_json", function(data)
{
for (var c = 0; c < data.customers.length; c++)
{
viewModel.allCustomers.push(data.customers[c]);
}
});
ko.applyBindings(viewModel);
PHP:
function get_json()
{
$eventData = array(
'customers' => array(array('name' => 'Bob', 'id' => 1), array('name' => 'John', 'id' => 2)),
'moreData' => array(),
'evenMoreData' => array()
);
echo json_encode($eventData);
}
这显示了所选样式的选择框,但是当我在其中单击时,没有出现任何选项。
当我在 View 模型中为客户创建一个本地 JS 数组并将其传递给 allCustomers 时,多选可以正常工作(请参阅我的 jsfiddle )所以它与从服务器获取数据有关,但我已经一直盯着这个看,看不出问题!
非常感谢任何帮助
最佳答案
在@Tyrsius 建议它可能不会在初始绑定(bind)后更新数据后,我发现了问题。
我将 $(element).trigger("liszt:updated");
添加到自定义绑定(bind)中,如下所示:
ko.bindingHandlers.chosen = {
update: function(element, valueAccessor, allBindingsAccessor, viewModel) {
$(element).chosen();
$(element).trigger("liszt:updated");
}
}
关于php - Knockout JS 和 Chosen 多选不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11369333/