好吧,所以我决定自己装订。这比我预期的要容易得多。我会把它贴在这里。我只是直接从源代码中撕下来并稍微修改了一下。变化真的很简单,我强烈建议你比较两者,看看我在做什么。现在,有一些警告。
a) 为了我自己的方便,我基本上硬编码了一些“约定”,因为我不太确定如何使它对任何类型模型都足够通用。基本上你应该看看我正在使用的视图模型,如果你不能/不想重现类似的东西,你可能不得不更改代码以反映这一点。但这很简单(使用 firebug :))
b)它正在为单选更新模型的选定值,但我没有尝试使用多选。我正在使用其他东西进行多项选择。但是我从原始的“选项”绑定中留下了该代码。
- -更新 - -
想通了 c. 它可以更新视图模型。
----结束更新---
c)如果您更改模型,我不确定它是否会更新选择。坦率地说,当我意识到我似乎无法让它更新常规选择框上的选择选项时,我正在测试它,所以我对此有点犹豫。我会在/如果我弄明白的时候更新。
d) 您必须包含 ensureDropdownSelectionIsConsistentWithModelValue 函数,因为它是 ko 中的“私有”函数,您无法从外部访问它。
function ensureDropdownSelectionIsConsistentWithModelValue(element, modelValue, preferModelValue) {
if (preferModelValue) {
if (modelValue !== ko.selectExtensions.readValue(element))
ko.selectExtensions.writeValue(element, modelValue);
}
// No matter which direction we're syncing in, we want the end result to be equality between dropdown value and model value.
// If they aren't equal, either we prefer the dropdown value, or the model value couldn't be represented, so either way,
// change the model value to match the dropdown.
if (modelValue !== ko.selectExtensions.readValue(element))
ko.utils.triggerEvent(element, "change");
}
ko.bindingHandlers['groupedSelect'] = {
'update': function (element, valueAccessor, allBindingsAccessor) {
if (ko.utils.tagNameLower(element) !== "select")
throw new Error("options binding applies only to SELECT elements");
var selectWasPreviouslyEmpty = element.length == 0;
var previousSelectedValues = ko.utils.arrayMap(ko.utils.arrayFilter(element.childNodes, function (node) {
return node.tagName && (ko.utils.tagNameLower(node) === "option") && node.selected;
}), function (node) {
return ko.selectExtensions.readValue(node) || node.innerText || node.textContent;
});
var previousScrollTop = element.scrollTop;
var value = ko.utils.unwrapObservable(valueAccessor());
value = value.groups();
var selectedValue = element.value;
// Remove all existing <option>s.
// Need to use .remove() rather than .removeChild() for <option>s otherwise IE behaves oddly (https://github.com/SteveSanderson/knockout/issues/134)
while (element.length > 0) {
ko.cleanNode(element.options[0]);
element.remove(0);
}
if (value) {
var allBindings = allBindingsAccessor();
if (typeof value.length != "number")
value = [value];
if (allBindings['optionsCaption']) {
var option = document.createElement("option");
ko.utils.setHtml(option, allBindings['optionsCaption']);
ko.selectExtensions.writeValue(option, undefined);
element.appendChild(option);
}
for (var a= 0, b = value.length; a < b; a++) {
var optGroup = document.createElement("optgroup");
ko.bindingHandlers['attr'].update(optGroup, ko.observable({label: value[a].label()}));
var children = ko.utils.unwrapObservable(value[a].children());
for (c=0, d=children.length; c<d; c++){
var option = document.createElement("option");
// Apply a value to the option element
var optionValue = typeof allBindings['optionsValue'] == "string" ? value[a].children()[c][allBindings['optionsValue']] : value[a].children()[c];
optionValue = ko.utils.unwrapObservable(optionValue);
ko.selectExtensions.writeValue(option, optionValue);
// Apply some text to the option element
var optionsTextValue = allBindings['optionsText'];
var optionText;
if (typeof optionsTextValue == "function")
optionText = optionsTextValue(value[a].children()[c]); // Given a function; run it against the data value
else if (typeof optionsTextValue == "string")
optionText = value[a].children()[c][optionsTextValue]; // Given a string; treat it as a property name on the data value
else
optionText = optionValue; // Given no optionsText arg; use the data value itself
if ((optionText === null) || (optionText === undefined))
optionText = "";
ko.utils.setTextContent(option, optionText);
optGroup.appendChild(option);
}
element.appendChild(optGroup);
}
// IE6 doesn't like us to assign selection to OPTION nodes before they're added to the document.
// That's why we first added them without selection. Now it's time to set the selection.
var newOptions = element.getElementsByTagName("option");
var countSelectionsRetained = 0;
for (var i = 0, j = newOptions.length; i < j; i++) {
if (ko.utils.arrayIndexOf(previousSelectedValues, ko.selectExtensions.readValue(newOptions[i])) >= 0) {
ko.utils.setOptionNodeSelectionState(newOptions[i], true);
countSelectionsRetained++;
}
}
element.scrollTop = previousScrollTop;
if (selectWasPreviouslyEmpty && ('value' in allBindings)) {
// Ensure consistency between model value and selected option.
// If the dropdown is being populated for the first time here (or was otherwise previously empty),
// the dropdown selection state is meaningless, so we preserve the model value.
ensureDropdownSelectionIsConsistentWithModelValue(element, ko.utils.unwrapObservable(allBindings['value']), /* preferModelValue */ true);
}
// Workaround for IE9 bug
ko.utils.ensureSelectElementIsRenderedCorrectly(element);
}
}
用法
<select data-bind="groupedSelect:FieldList,optionsText:'Text',optionsValue:'Value',optionsCaption:'-- Please Select --',value:FieldEntityId">
视图模型
"FieldList":{
"groups":[
{"label":"SomeGroup1","children":[
{"Text":"field1","Value":"1"},
{"Text":"field2","Value":"2"}
]},
{"label":"SomeGroup 2","children":[
{"Text":"field3","Value":"3"},
{"Text":"field4","Value":"4"}
]}
]
}
我想如果您有任何问题或意见,请告诉我。
还让我解释一下为什么模特看起来,嗯,有点奇怪。我真的只是从看起来像这样的 C# 模型序列化
public class GroupSelectViewModel
{
public GroupSelectViewModel()
{
groups = new List<SelectGroup>();
}
public List<SelectGroup> groups { get; set; }
}
public class SelectGroup
{
public string label { get; set; }
public IEnumerable<SelectListItem> children { get; set; }
}
SelecListItem 是使用帕斯卡符号的 ac# 类。