可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have the following models:
var allCategories = [{ id: 1, name: 'Red'}, { id: 5, name: 'Blue'}]; function model() { self = this; self.name = ko.observable(""); self.categoryId = ko.observable(-1); self.categoryName = ko.computed(function() { if (self.categoryId() == -1) return ""; return getCategoryNameById(self.categoryId()).name; }); } function getCategoryNameById(id) { return _.find(allCategories, function(cat) { return cat.id == id; }); }
I want to offer a dropdown to select the category but I have no clue how to bind that. Maybe I've used the wrong approach with my models but that's most likely how I get my data from the server so I've tried to wrap my JS around that.
I tried something like this:
<select data-bind="options: categories, optionsText: 'name', value: 'id', optionsCaption: 'Categorie...'"></select>
But I don't get how to connect the dropdown value to the model categoryId
.
Here is a fiddle with a working binding for the name property.
回答1:
For your list box you need to specify: options
, optionsText
, optionsValue
, and value
. value
(which is the currently selected value) should point to your model.categoryId()
. And optionsValue
is the property name where to get values for the list:
<select data-bind="options: categories, optionsText: 'name', optionsValue: 'id', value: $root.model.categoryId(), optionsCaption: 'Categorie...'"></select>
And that's it. And the working fiddle: http://jsfiddle.net/Y7Nrc/
回答2:
According to Max Schmelevs answer, which is correct, this functionality doesn't doesn't change the JSON object when you change the item from a dropdown.
So here are my corrections for his code:
HTML Code:
<div id="container"> <!-- Here I've added valueUpdate on keydown --> <input data-bind="value: model.name, valueUpdate:'afterkeydown'" /> <!-- NOTE: Here you should call value like $root.model.categoryId --> <select data-bind="options: categories, optionsText: 'name', optionsValue: 'id', value: $root.model.categoryId, optionsCaption: 'Categorie...'"></select> <span data-bind="text: ko.toJSON($data.model)"></span> </div>
Javascript Code:
var allCategories = [ {id: 1, name: 'Red'}, {id: 5, name: 'Blue'}]; function model() { self = this; self.name = ko.observable(""); self.categoryId = ko.observable(1); self.categoryName = ko.computed(function() { //NOTE: Here we should check if categoryId() is defined or not if (!self.categoryId()) return ""; return getCategoryNameById(self.categoryId()).name; }); } function getCategoryNameById(id) { return _.find(allCategories, function(cat) { return cat.id == id; }); } var viewModel = {}; viewModel.model = new model(); viewModel.categories = allCategories; ko.applyBindings(viewModel, document.getElementById('container'));
!!!IMPORTANT!!!
If this approach answers your question, please select Max Shmelev's answer as correct, not mine, because I've just put some remarks in his code.