我有以下型号:
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;
    });
}
我想提供一个下拉列表来选择类别,但我不知道如何绑定它.也许我对我的模型使用了错误的方法,但这很可能是我如何从服务器获取数据,所以我试图将我的JS包装起来.
我试过这样的事情:
<select data-bind="options: categories, optionsText: 'name', value: 'id', optionsCaption: 'Categorie...'"></select>
但我不知道如何将下拉值连接到模型categoryId.
Max*_*lev 21
为了您的列表框,你需要指定:options,optionsText,optionsValue,和value.
value(这是当前选择的值)应指向您的model.categoryId().并且optionsValue是获取列表值的属性名称:
<select data-bind="options: categories, optionsText: 'name', optionsValue: 'id', value: $root.model.categoryId(), optionsCaption: 'Categorie...'"></select>
就是这样.工作小提琴:http://jsfiddle.net/Y7Nrc/
小智 11
根据Max Schmelevs的回答,这是正确的,当您从下拉列表中更改项目时,此功能不会更改JSON对象.
所以这是我对他的代码的更正:
HTML代码:
<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代码:
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'));
!!!重要!!!
如果这种方法回答了你的问题,请选择Max Shmelev的答案是正确的,而不是我的,因为我只是在他的代码中加了一些评论.
| 归档时间: | 
 | 
| 查看次数: | 14756 次 | 
| 最近记录: |