我正在为select2
提供以下KO绑定:
ko.bindingHandlers.select2 = {
init: function (element, valueAccessor, allBindings) {
$(element).select2(valueAccessor());
// if a value binding exists, subscribe to it
// to clear the select2 plugin when the value is empty
var valueBindingAccessor = allBindings.get('value');
if (valueBindingAccessor) {
valueBindingAccessor.subscribe(function (val) {
if (val == undefined) {
$(element).select2("val", "");
}
});
}
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).select2('destroy');
});
}
};
以下是我的意见:
<input type="text" class="form-control" data-bind="value: $root.Name, attr: { 'placeholder': DisplayName }, select2: { minimumInputLength: 1, query: function(query,key){ $root.getAutoCompleteSelect2(query, FieldName)}, allowClear: true, multiple: true}">
以下是我从服务器获取值的ajax函数:
getAutoCompleteSelect2: function (query,key ) {
CallAjaxWithData('Resume/GetAutoCompleteResult', 'GET', { key: key, enteredValue: query.term, topNRows: R1ViewModel.TopNRows }, getAutoCompleteListSuccess, getAutoCompleteListFailure);
function getAutoCompleteListSuccess(data) {
var newData = [];
$.each(data, function (index, text) {
newData.push({
id: text
, text: text
});
});
query.callback({
results: newData
});
}
当我动态地将逗号分隔值分配给Name
observable时,这些值在select2
ul中没有绑定,即我无法看到{{1}中的值} 控制。如何解决这个问题?
修改 自动填充功能也会显示已选择的值,但已选中的项目不应出现在自动填充结果中。我们能解决这个问题吗?
EDIT2:
我已按以下方式修改了我的绑定:
select2
我收到以下错误:
ko.bindingHandlers.select2 = {
init: function (element, valueAccessor, allBindings) {
$(element).select2(valueAccessor());
// if a value binding exists, subscribe to it
// to clear the select2 plugin when the value is empty
var valueBindingAccessor = allBindings.get('value');
if (valueBindingAccessor) {
valueBindingAccessor.subscribe(function (val) {
if (val == undefined) {
$(element).select2("val", "");
}
else {
$(element).select2("val", val.split(','));// splitting the comma separated string to get a string array
}
});
}
ko.utils.domNodeDisposal.addDisposeCallback(element, function () {
$(element).select2('destroy');
});
}
};