击倒绑定选择与自定义对象的可观察属性

Knockout bind select with custom object with observable properties

本文关键字:观察 属性 对象 自定义 绑定 选择      更新时间:2023-09-26

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

第一个对象是Property,它的headquarter_idko.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>

但是我一直得到:

Uncaught ReferenceError: cannot to process binding "options: function (){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/

好了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之间缺少单引号。

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/