Associative observable arrays

291 views
Skip to first unread message

Bombo

unread,
Apr 20, 2011, 10:57:39 AM4/20/11
to KnockoutJS, bros...@sitrion.com
Hello everybody,

is there any way to use javascript pseudo-associative array
functionality with observable arrays?
I would like to change the selected value of one dropdown list in
dependence of the selection of another one. Both dropdowns are filled
with KOs options binding. I would like to avoid using the optionsValue
binding, so I have access to the actual selected object in both cases.
The view model elements associated with the specific dropdowns are:

var value1 = function(key, text, value2) {
this.key = key;
this.text = text;
this.value2 = val2;
};
var value2 = function(key, text) {
this.key = key;
this.text = text;
};

The val2 property of each value1 should correspond to the key property
of some value2 object. The second dropdown's selected value is binded
to viewModel.selectedValue2, which should be changed by manual
subscription:

viewModel.selectedValue1.subscribe(function(newValue) {
this.selectedValue2(this.values2()[newValue.val2]);
}, viewModel);

The values2 array would be of form:

{
"key1" : { "key" : "key1", "text" : "text1" },
"key2" : { "key" : "key2", "text" : "text2" },
"key3" : { "key" : "key3", "text" : "text3" },
...
}

I hope, you get, what I mean.

Thanks in advance!

Boris

rpn

unread,
Apr 20, 2011, 11:34:17 PM4/20/11
to knock...@googlegroups.com, bros...@sitrion.com
In the current code, you would not be able to bind your values2 object to the dropdown.

I think that typically you would do something like this: http://jsfiddle.net/rniemeyer/xdNp5/

In that sample, the second dropdown updates the value2 property of the corresponding value1 object directly (no selectedValue2 observable).  If they should not be linked, then you could just use a selectedValue2 observable like you are doing.

As far as the associative array idea, you could loop through the array and create this index object for lookup, then use it in the manual subscription to update the second observable.  Maybe this was more what you had in mind: http://jsfiddle.net/rniemeyer/29ZGw/

Hope this helps.  Let me know if I misunderstood your question.



Bombo

unread,
Apr 21, 2011, 2:38:40 AM4/21/11
to KnockoutJS
You understood correctly! The second solution is exactly what I have
wanted!

You saved me from another headache! Thank you! :)

Greets,
Boris
Reply all
Reply to author
Forward
0 new messages