修改 将行单击方法更改为:
this.addAL = function() {
this.selectedState.push("Alabama(AL)")
}
更新observable,但Select2框仍然不显示标记。我相应地更新了codepen。
原始问题
所以我有以下设置:
实际的Select2框工作正常,但是如果我尝试在单击按钮后选择选择中的一个选项,则它不起作用。到目前为止,这是我的代码:
HTML:
<select multiple="multiple" data-bind="selectedOptions: selectedState, select2: { data: states, placeholder: 'Select a State', tags: true, allowClear: true, formatResult: format }" class="select2" style="width: 200px"></select>
Selected: <span data-bind="text: selectedState"></span>
<br/>
<br/>
<button data-bind='click:addAL'>Add Alabama</button>
JavaScript的:
ko.bindingHandlers.select2 = {
init: function(el, valueAccessor, allBindingsAccessor, viewModel) {
ko.utils.domNodeDisposal.addDisposeCallback(el, function() {
$(el).select2('destroy');
});
var allBindings = allBindingsAccessor(),
select2 = ko.utils.unwrapObservable(allBindings.select2);
$(el).select2(select2);
},
update: function (el, valueAccessor, allBindingsAccessor, viewModel) {
var allBindings = allBindingsAccessor();
if ("value" in allBindings) {
if ((allBindings.select2.multiple || el.multiple) && allBindings.value().constructor != Array) {
$(el).val(allBindings.value().split(',')).trigger('change');
}
else {
$(el).val(allBindings.value()).trigger('change');
}
} else if ("selectedOptions" in allBindings) {
var converted = [];
var textAccessor = function(value) { return value; };
if ("optionsText" in allBindings) {
textAccessor = function(value) {
var valueAccessor = function (item) { return item; }
if ("optionsValue" in allBindings) {
valueAccessor = function (item) { return item[allBindings.optionsValue]; }
}
var items = $.grep(allBindings.options(), function (e) { return valueAccessor(e) == value});
if (items.length == 0 || items.length > 1) {
return "UNKNOWN";
}
return items[0][allBindings.optionsText];
}
}
$.each(allBindings.selectedOptions(), function (key, value) {
converted.push({id: value, text: textAccessor(value)});
});
$(el).select2("data", converted);
}
}
};
function format(state) {
var originalOption = state.element;
return state.text.toUpperCase();
}
function State(id, text, children, disabled) {
this.id = id;
this.text = text;
this.disabled = disabled || false;
this.children = children;
}
function City(id,text,children,disabled) {
this.id = id;
this.text = text;
this.disabled = disabled || false;
this.children = children;
}
State.prototype.toString = City.prototype.toString =function() {
return this.text + "(" + this.id + ")";
};
var ViewModel = function () {
this.states = [
new State("AL", "Alabama",[],true),
new State("AK", "Alaska", [ new City("JU", "Juneau")]),
new State("AZ", "Arizona"),
/* ... */
new State("WV", "West Virginia"),
new State("WI", "Wisconsin"),
new State("WY", "Wyoming")
];
this.selectedState = ko.observableArray([]);
this.addAL = function() {
this.selectedState().push(new State("AL", "Alabama"))
}
};
ko.applyBindings(new ViewModel());
这是一个Codepen,其中包含我当前的代码:
http://codepen.io/anon/pen/ONBVYz
非常感谢任何领导/提示/建议,谢谢!