我在knockout.js中实现了一个分组选择框,其灵感来自(我通过观察看出来) KnockoutJS - Binding value of select with optgroup and javascript objects 作者:RP Niemeyer 但它有点不同。它看起来像这样。
<select name="Field" data-bind="foreach: FieldList.Groups, value:Field" >
<optgroup data-bind="attr: {label: Label}, foreach: Children">
<option data-bind="text: Text, value: Value"></option>
</optgroup>
</select>
我的viewmodel看起来像
var viewmodel = {
Field: 2,
Groups:{
Label:"Field 1",
Children:[
{ Text:"Field1", Value:1 },
{ Text:"Field2", Value:2 }
]
}
类似的东西,无论如何它都很棒。但是,我真的需要将“请选择...”作为第一个选项。
鉴于它是一个foreach循环
a)optionsCaption绑定不起作用
b)我不能只在那里添加选项,因为每个组都会重复这个选项。
只是为了确保没有人可以帮助我,我会添加这个约束。我实际上是代码生成(只是服务器上的一些C#)html,虽然我可以做很多自定义的东西我不能添加任意文本,即注释到输出。也就是说我不能做无容器的foreach因为我只能发出htmltags而不是html评论。
UGG。
如果有任何想法,请告诉我,我会非常感激。 谢谢, [R
答案 0 :(得分:4)
好的,所以我决定做自己的绑定。这比我预想的要容易得多。我会在这里发布。我刚从源代码中直接撕掉了它并稍微修改了一下。这些变化非常简单,我强烈建议你比较两者,看看我在做什么。现在,有一些警告。
a)为了方便起见,我基本上硬编了一些“约定”,因为我不确定如何使它对任何类型的模型都足够通用。基本上你应该看看我正在使用的视图模型,如果你不能/不想重现类似的东西你可能需要更改代码以反映它。但它很简单(使用firebug :))
b)它正在为单个选择更新模型的选定值,但我没有尝试使用多个选择。我正在使用其他东西进行多重选择。但是我从最初的“选项”绑定中留下了代码。
--- ---更新
想出了c。它可以更新viewmodel。
----结束更新---
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是一个使用pascal表示法的c#类。