【问题标题】:Knockout bind select with custom object with observable properties具有可观察属性的自定义对象的淘汰赛绑定选择
【发布时间】:2015-10-16 14:17:40
【问题描述】:

我正在尝试将 <select> 与 Knockout 绑定。在我的 ViewModel 中,我有 2 个不同的对象,每个对象都有可观察的属性。

第一个对象是Property,它有一个headquarter_id 作为ko.observable()。 第二个对象是Headquarter,它有一个id 和一个name,都是ko.observable()

我正在尝试做的是将选择与ko.observableArray()Headquarter 对象绑定,如下所示:

<select id="headquarters" data-bind="options: HeadquarterOptions, optionsText: name, optionsValue: id, optionsCaption: '--Select--', value: Property().headquarter_id"></select>

但我不断得到:

未捕获的 ReferenceError:无法处理绑定“选项:函数 (){return HeadquarterOptions }”
消息:id 未定义

这是我的 ViewModel 的样子:

var Property = function () {
    var self = this;
    self.headquarter_id = ko.observable();
}

var Headquarter = function (id, name) {
    var self = this;
    self.id = ko.observable(id);
    self.name = ko.observable(name);
}

var headquarterOptions = [
        new Headquarter(1, "hq 1"),
        new Headquarter(2, "hq 2"),
        new Headquarter(3, "hq 3"),
    ]

var PropertiesViewModel = function (app, dataModel) {
    var self = this;
    self.Property = ko.observable(new Property());
    self.HeadquarterOptions = ko.observableArray(headquarterOptions);
}
    
ko.applyBindings(PropertiesViewModel);

我怎样才能做到这一点?
这是我目前的小提琴:http://jsfiddle.net/juandozco/dzwnb05b/

【问题讨论】:

    标签: javascript select knockout.js data-binding bind


    【解决方案1】:

    你去http://jsfiddle.net/dzwnb05b/4/

    <select class="form-control" id="headquarter" data-bind="options: HeadquarterOptions, optionsText: 'name', optionsValue: 'id', optionsCaption: '--Select--', value: Property().headquarter_id"></select>
    

    您在 name 和 id 周围缺少单引号。

    【讨论】:

    • 当然了!非常感谢,没注意。因此浪费了很多时间。
    【解决方案2】:

    optionsValueoptionsText 应声明为函数而不是值 (http://knockoutjs.com/documentation/options-binding.html):

    optionsText: function(item) {return item.name; }
    optionsValue: function(item){ return item.id; }
    

    查看更新的小提琴:http://jsfiddle.net/dzwnb05b/3/

    【讨论】:

    • 它有效,但@Beyond Programming 给出了正确答案。谢谢你。
    猜你喜欢
    • 2017-04-11
    • 2013-12-21
    • 2014-03-07
    • 2012-05-31
    • 2014-08-22
    • 2013-05-19
    • 2011-12-20
    • 2012-09-23
    • 2013-05-04
    相关资源
    最近更新 更多