I was looking for similar functionality in something I was throwing together yesterday and couldn't find it, so I ended up just changing what I was storing in the value attributes. Sometimes that's the simplest solution.
Here's a quick and kind of ugly solution to the problem using jQuery:
HTML
<div data-bind="text: dropdownText"></div>
<select data-bind="value: dropdownValue" id="dropdown">
<option value="1">Value1</option>
<option value="2">Value2</option>
</select>
JS
function ViewModel() {
var self = this;
this.dropdownValue = ko.observable();
this.dropdownText = ko.computed(function() {
return $("#dropdown option[value='" + self.dropdownValue() + "']").text();
});
};
ko.applyBindings(new ViewModel());
Live example: http://jsfiddle.net/5PkBF/
If you were looking to do this in multiple places, it'd probably be best to write a custom binding, e.g.:
HTML
<div data-bind="text: dropdownValue"></div>
<select data-bind="selectedText: dropdownValue">
<option value="1">Value1</option>
<option value="2">Value2</option>
</select>
JS
ko.bindingHandlers.selectedText = {
init: function(element, valueAccessor) {
var value = valueAccessor();
value($("option:selected", element).text());
$(element).change(function() {
value($("option:selected", this).text());
});
},
update: function(element, valueAccessor) {
var value = ko.utils.unwrapObservable(valueAccessor());
$("option", element).filter(function(i, el) { return $(el).text() === value; }).prop("selected", "selected");
}
};
function ViewModel() {
this.dropdownValue = ko.observable();
};
ko.applyBindings(new ViewModel());
Live example: http://jsfiddle.net/5PkBF/1/
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…