【发布时间】:2014-07-12 11:29:10
【问题描述】:
我通过这个简单的绑定使用 select2 和 knockoutJs:
ko.bindingHandlers.select2 = {
init: function (element, valueAccessor, allBindings, viewModel, bindingContext) {
var options = ko.toJS(valueAccessor()) || {};
setTimeout(function () {
$(element).select2(options);
}, 0);
}
};
标记:
<select class="select2" style="width:100%" data-bind="optionsCaption: '',options: $root.items,optionsText: 'description',optionsValue: 'id', value: $root.selectedItem,select2: { placeholder: 'Select an item...',allowClear: true }"></select>
有效!现在我在 Select2 中启用了allowClear 选项,以将下拉列表清除为Select an item... 之类的占位符值。
如果我点击x 图标下拉菜单正确设置占位符但敲除不会更新可观察的绑定值!
我想我必须更改自定义绑定添加如下内容:
setTimeout(function () {
$(element).select2(options).on("select2-removed", function (e) {
ko.bindingHandlers.value.update(element, function () { return ''; });
});
...
但它不会工作!
【问题讨论】:
-
您能否提供一个带有您的代码的jsfiddle
-
setTimeout 是怎么回事?另外,我只能看到“init”实现,如果你有的话,你能在 bindingHandler 中显示你的“update”实现吗?
标签: javascript jquery knockout.js