简体   繁体   中英

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/

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)

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/

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">

When you are binding against objects in the value binding, then they need to be a reference to the same object.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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