[英]In knockout when using <select> how to get the selected item to select the correct item on startup when you have an object
given this coffeescript 给出这个咖啡脚本
data =
Foo: "B"
Foos: [ "A", "B" ]
Blah:
Id: 2
Name: "B"
Blahs: [
Id: 1
Name: "A"
,
Id: 2
Name: "B"
]
class Vm
constructor: (data) ->
@Blah = ko.observable()
ko.mapping.fromJS data, {}, this
vm = new Vm(data)
console.log vm
ko.applyBindings vm;
and then given these two dropdown bindings... 然后给出这两个下拉绑定...
<select data-bind="options: Blahs,optionsText: 'Name', value: Blah">
<select data-bind="options: Foos, value: Foo">
the fiddle:- 小提琴:
http://jsfiddle.net/keith_nicholas/3eYHd/ http://jsfiddle.net/keith_nicholas/3eYHd/
The strings of Foo sets the selected option on startup correctly, the one with objects, Blah, doesn't ( in fact it changes the selected item to be the first in the list) Foo的字符串在启动时正确设置了选定的选项,而带有对象Blah的字符串则没有(实际上,它将选定的项更改为列表中的第一项)
Is there are simple way to make the select with objects act the same as the one with strings? 有没有简单的方法可以使带对象的选择行为与带字符串的选择相同?
Note: I can do something like 注意:我可以做类似的事情
http://jsfiddle.net/keith_nicholas/LJpJw/ http://jsfiddle.net/keith_nicholas/LJpJw/
replaceWithMatching = (prop, list, match) ->
prop (x for x in list when x[match]() == prop()[match]())[0]
and then 接着
replaceWithMatching @Blah, @Blahs(), "Id"
to map the existing object to one that exists in the list. 将现有对象映射到列表中存在的对象。 But I was looking for something a bit cleaner / declarative, perhaps something like :-
但是我一直在寻找更简洁/声明性的东西,也许像:-
like <select data-bind="options: Blahs,optionsText: 'Name', matchOn: 'Id', value: Blah">
像
<select data-bind="options: Blahs,optionsText: 'Name', matchOn: 'Id', value: Blah">
When you are binding against objects in the value
binding, then they need to be a reference to the same object. 当您绑定
value
绑定中的对象时,则它们需要是对同一对象的引用。
Basically: 基本上:
var a = { name: "Bob" };
var b = { name: "Bob" };
var c = b;
alert(a === b) //false
alert(b === c) //true
So, in your sample you could define the array of choices first and then initialize your selected value to one of the objects in that array. 因此,在示例中,您可以先定义选择数组,然后将所选值初始化为该数组中的一个对象。
Here is your sample updated: http://jsfiddle.net/rniemeyer/ampys/ 这是您的示例更新: http : //jsfiddle.net/rniemeyer/ampys/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.