我想显示名称属性,但我需要存储 Id。
由于目前没有针对 HTML5 的 Knockout 绑定<datalist>
,所以我做了一个。
我试图从绑定中尽可能多地借用select
,所以支持options
,optionsText
和optionsValue
。您可以通过 指定一个可观察的目标value
。
ko.bindingHandlers.datalist = (function () {
function getVal(rawItem, prop) {
var item = ko.unwrap(rawItem);
return item && prop ? ko.unwrap(item[prop]) : item;
}
function findItem(options, prop, ref) {
return ko.utils.arrayFirst(options, function (item) {
return ref === getVal(item, prop);
});
}
return {
init: function (element, valueAccessor, allBindingsAccessor) {
var setup = valueAccessor(),
textProperty = ko.unwrap(setup.optionsText),
valueProperty = ko.unwrap(setup.optionsValue),
dataItems = ko.unwrap(setup.options),
myValue = setup.value,
koValue = allBindingsAccessor().value,
datalist = document.createElement("DATALIST");
// create an associated <datalist> element
datalist.id = element.getAttribute("list");
document.body.appendChild(datalist);
// when the value is changed, write to the associated myValue observable
function onNewValue(newVal) {
var dataItems = ko.unwrap(setup.options),
selectedItem = findItem(dataItems, textProperty, newVal),
newValue = selectedItem ? getVal(selectedItem, valueProperty) : void 0;
if (ko.isWriteableObservable(myValue)) {
myValue(newValue);
}
}
// listen for value changes
// - either via KO's value binding (preferred) or the change event
if (ko.isSubscribable(koValue)) {
koValue.subscribe(onNewValue);
} else {
ko.utils.registerEventHandler(element, "change", function () {
onNewValue(this.value);
});
}
// init the element's value
// - either via the myValue observable (preferred) or KO's value binding
if (ko.isObservable(myValue) && myValue()) {
element.value = getVal(findItem(dataItems, valueProperty, myValue()), textProperty);
} else if (ko.isObservable(koValue) && koValue()) {
onNewValue(koValue());
}
},
update: function (element, valueAccessor) {
var setup = valueAccessor(),
datalist = element.list,
dataItems = ko.unwrap(setup.options),
textProperty = ko.unwrap(setup.optionsText);
// rebuild list of options when an underlying observable changes
datalist.innerHTML = "";
ko.utils.arrayForEach(dataItems, function (item) {
var option = document.createElement("OPTION");
option.value = getVal(item, textProperty);
datalist.appendChild(option);
});
ko.utils.triggerEvent(element, "change");
}
};
})();
我希望我做对了大部分。欢迎指正和改进建议。
你会像这样使用它:
<input list="company" data-bind="datalist: {
options: companies,
optionsValue: 'id',
optionsText: 'name',
value: selectedCompany
}" />
笔记。
- 无需
<datalist>
在 HTML 中单独创建。自定义绑定会为您做到这一点。
- 但是,您必须提供元素的
list=""
属性。<input>
到目前为止,我还没有发现在 JavaScript 中动态设置它的方法。
value
是可选的,但如果你提供它,它必须是可观察的。
- 您仍然可以
value
在datalist
. 它将包含<input>
显示的任何文本(这并不奇怪)。但是,写入内置值也会更新该datalist
值,反之亦然。
- 该
datalist
值具有优先权,并将在视图模型初始化时覆盖内置值。之后他们保持同步。
options
应该是一个对象数组(普通的旧的或可观察的)——在这种情况下是公司)。
optionsText
并且optionsValue
是应该映射到选项属性的字符串。
- 您不必使用
optionsValue
- 在这种情况下,整个对象(单个公司)将存储在value
. 我宁愿只存储 ID。
- 当前,设置对
change
事件作出反应。这意味着您的视图模型在您离开输入字段之前不会更新。
- 在 Chrome 32、YMMV 上测试。正如我所说,欢迎评论和更正。
下面是一个演示,从原始fiddle复制而来。
function main() {
function Company(company) {
this.id = company.Id;
this.name = company.Name;
this.state = company.State.name;
}
function ViewModel(sampleData) {
var self = this;
self.companies = ko.observableArray();
ko.utils.arrayForEach(sampleData, function (companyData) {
self.companies.push(new Company(companyData));
});
// KO's "value" binding _can_ supply a start value
self.val = ko.observable("Microsoft");
// ... but it is overridden by datalist's "value" binding - in any case you can use both
self.selectedCompany = ko.observable(1);
}
// -----------------------------------------------------------------------------------
ko.applyBindings(new ViewModel([{
Id: 1,
Name: "Apple",
State: {
name: "California"
}
}, {
Id: 2,
Name: "Microsoft",
State: {
name: "Washington"
}
}, {
Id: 3,
Name: "IBM",
State: {
name: "New York"
}
}]));
}
// -----------------------------------------------------------------------------------
ko.bindingHandlers.datalist = (function () {
function getVal(rawItem, prop) {
var item = ko.unwrap(rawItem);
return item && prop ? ko.unwrap(item[prop]) : item;
}
function findItem(options, prop, ref) {
return ko.utils.arrayFirst(options, function (item) {
return ref === getVal(item, prop);
});
}
return {
init: function (element, valueAccessor, allBindingsAccessor) {
var setup = valueAccessor(),
textProperty = ko.unwrap(setup.optionsText),
valueProperty = ko.unwrap(setup.optionsValue),
dataItems = ko.unwrap(setup.options),
myValue = setup.value,
koValue = allBindingsAccessor().value,
datalist = document.createElement("DATALIST");
// create an associated <datalist> element
datalist.id = element.getAttribute("list");
document.body.appendChild(datalist);
// when the value is changed, write to the associated myValue observable
function onNewValue(newVal) {
var dataItems = ko.unwrap(setup.options),
selectedItem = findItem(dataItems, textProperty, newVal),
newValue = selectedItem ? getVal(selectedItem, valueProperty) : void 0;
if (ko.isWriteableObservable(myValue)) {
myValue(newValue);
}
}
// listen for value changes
// - either via KO's value binding (preferred) or the change event
if (ko.isSubscribable(koValue)) {
koValue.subscribe(onNewValue);
} else {
ko.utils.registerEventHandler(element, "change", function () {
onNewValue(this.value);
});
}
// init the element's value
// - either via the myValue observable (preferred) or KO's value binding
if (ko.isObservable(myValue) && myValue()) {
element.value = getVal(findItem(dataItems, valueProperty, myValue()), textProperty);
} else if (ko.isObservable(koValue) && koValue()) {
onNewValue(koValue());
}
},
update: function (element, valueAccessor) {
var setup = valueAccessor(),
datalist = element.list,
dataItems = ko.unwrap(setup.options),
textProperty = ko.unwrap(setup.optionsText);
// rebuild list of options when an underlying observable changes
datalist.innerHTML = "";
ko.utils.arrayForEach(dataItems, function (item) {
var option = document.createElement("OPTION");
option.value = getVal(item, textProperty);
datalist.appendChild(option);
});
ko.utils.triggerEvent(element, "change");
}
};
})();
main();
.hint {
color: silver;
font-size: 80%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.0.0/knockout-min.js"></script>
<input list="company" type="text" placeholder="Select a company..." data-bind="value: val, datalist: {
options: companies,
optionsValue: 'id', /* try removing 'optionsValue' and see what happens to the view model */
optionsText: 'name',
value: selectedCompany
}" />
<span class="hint">(note the "change" event occurs after the field loses focus!)</span>
<hr />
<p>View Model:</p>
<pre data-bind="text: ko.toJSON($root, null, 2)"></pre>