敲除绑定密钥值对象到下拉(knockout bind a key value object to d

2019-08-03 05:55发布

我有以下型号:

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

这里是小提琴与name属性工作结合。

Answer 1:

为了您的列表框,你需要指定: optionsoptionsTextoptionsValuevaluevalue (这是当前所选的值)应指向您model.categoryId()optionsValue是属性名称,其中获得值列表:

<select data-bind="options: categories, optionsText: 'name', optionsValue: 'id', value: $root.model.categoryId(), optionsCaption: 'Categorie...'"></select>

仅此而已。 和工作小提琴: http://jsfiddle.net/Y7Nrc/



Answer 2:

据马克斯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'));

!!!重要!!!

如果这种方法回答您的问题,请选择最高什梅廖夫的答案是正确的,不是我的,因为我只是把一些言论在他的代码。



文章来源: knockout bind a key value object to dropdown
标签: knockout.js