简体   繁体   English

剔除选项文本/选项值绑定无效

[英]knockout optionsText / optionsValue bindings won't work

Why does this binding fail with a "value not found" exception? 为什么此绑定失败并显示“找不到值”异常?

<select data-bind="options: $root.arr, optionsValue: key, optionsText: value"></select>

The options array's data is this: options数组的数据是这样的:

ko.observableArray ([ 
  {key: 'foo', value: '1'}, 
  {key: 'bar', value: '2'}
])

I already solved my own problem but laying down a StackOverflow breadcrumb trail so others won't waste their time like I did trying to figure this out. 我已经解决了自己的问题,但是铺设了StackOverflow面包屑路径,这样其他人就不会像我试图弄清楚这一点那样浪费时间。 ;-) ;-)

Quotes are required around property names used in optionsText and optionsValue. 在optionsText和optionsValue中使用的属性名称必须带引号。 Like this: 像这样:

<select data-bind="options: $root.arr, optionsValue: 'key', optionsText: 'value'"></select>

I'd assumed that: 我以为:

  1. The options binding created a new binding context like with and foreach do options绑定创建了一个新的绑定上下文,如withforeach do
  2. The optionsValue and optionsText worked like the text binding where you can just specify the property name and KO magically binds to the properties optionsValue和optionsText就像text绑定一样工作,您可以在其中指定属性名称,然后KO神奇地绑定到属性

Both assumptions were wrong, as I realized after an hour of stepping through the KO sources trying to figure out what I was doing wrong. 这两个假设都是错误的,正如我在经过一个小时的KO消息源试图弄清楚我在做错什么之后意识到的那样。 Arrrrgh! Arrrrgh!

Instead, if you're not using a function to pull out the value or text for each option, and you want to access a property instead, you need to enclose the property name in quotes. 相反,如果您不使用函数来提取每个选项的值或文本,而是想访问属性,则需要将属性名称括在引号中。 This is shown in the documentation if you read the example code carefully enough. 如果您足够仔细地阅读示例代码,则这将在文档中显示。 Which I didn't. 我没有。 ;-( ;-(

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM