Take the 2-minute tour ×

I'm having difficulties handling select change the same way the build in 'click' handler on a span/button/whatever does in Knockout. Easy scenario, when the currently selected item changes, I want to call a function with a reference to the respective item in a foreach:

<ul id="storeList" data-bind="foreach: $data">
<span data-bind="text: StaticName, click: $root.storeModel.editStore"></span>

In editStore, store is a reference to the complete current store object:

p.editStore = function(store, event) {
            location.hash = 'Butiker/Edit/' + ko.utils.unwrapObservable(store.StoreId);
            var el = event.target;


Now I want to use a select instead:

<select data-bind="options: $data, optionsText: 'StaticName', optionsValue: 'StoreId', optionsCaption: 'Choose store', event : { change: $root.storeModel.editStore }"></select>

This works but in the editStore function, nothing is passed as the first parameter.

I can do value: currentEditItem on the select, but I want to do extra stuff when that observable has its data updated. I can't subscribe to it, because that only gives me the new string value of that particular property...not the object itself.

Why does click have to give me everything I need, whereas select change leaves me dealing with a small portion of the object I'm interested in?

share|improve this question
What happens when you do: event: { change: function(a, b) { console.log(a,b); } } –  paulslater19 May 22 '12 at 12:22
The result is that parameter a is $data (all the stores), meaning I don't know which one was selected. –  grilledtomatos May 22 '12 at 12:28
add comment

1 Answer

up vote 0 down vote accepted

EDIT: You're right, I was getting confused with selectedOptions.

This seems to work, though: http://jsfiddle.net/8pVuV/2/ The console.log returns the object, not the string.

share|improve this answer
selectedOptions only work on multiple-select list, mine is not. And as I wrote in the original post, subscribing to an observable won't do me any good, the only thing newVal is gonna return is the value of optionsValue. I need the whole object, exactly what the click handler does. –  grilledtomatos May 22 '12 at 13:16
@user1382035 you're right. Updated the answer –  paulslater19 May 22 '12 at 13:29
What I can do, is this. But how will this affect performance seeing that there will be up to 200 stores in the list? var store = ko.utils.arrayFirst(p.stores(), function(s) { return s.StoreId() === newVal; }); p.editStore(store, null); –  grilledtomatos May 22 '12 at 13:31
Edit - I now see that if you set optionsValue, it will change what the observable value is - jsfiddle.net/8pVuV/3 . Do you require the optionsValue property to be set? –  paulslater19 May 22 '12 at 13:38
Wow, great catch! Removing the optionsValue property causes the whole object being bound back to the value property. Thanks man! –  grilledtomatos May 22 '12 at 13:39
show 1 more comment

Your Answer


