Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind text to property of child object

Using knockout.js, is it possible to bind to a property of a child object of a JSON object from the server? Specifically, if I'm given an object from the server that looks like this:

var obj = {
    list: [ { key: "a", value: 1 },
            { key: "b", value: 2 },
            { key: "c", value: 3 }        
        ],
    selected: {
        key: "",
        value: null  
    }
};

I create a viewModel from this javascript object via the "mapping" plugin:

var viewModel = ko.mapping.fromJS(obj);

And I bind list to a <select> tag like so:

<select data-bind="options: list, optionsText: 'key', 
                   optionsValue: 'value', 
                   value: selected">
</select>

I've assigned the value to be the selected property of my viewModel. This means, upon selecting an option, I can successfully query viewModel.selected.key() and viewModel.selected.value() in code and get the up-to-date values.

However, I am unable to bind the selected item's key or value data to be displayed on a span. For instance, this doesn't display my selected value:

<span data-bind="text: selected.value"></span>

Can I do what I want? Do I need to resort to using a real simple template to establish proper context (ie: selected)?

I have an example of the situation here. I've even tried specifically mapping the child selected object to be an observable itself, but with no luck (see commented out mapping call with the additional options).

like image 457
kdawg Avatar asked Feb 24 '23 08:02

kdawg


1 Answers

You were on the right track with the mapping options. You would want selected to be an observable, so your UI updates when you make changes in the dropdown. In your case, it could even be empty.

One thing to note is that when the mapping plugin deals with an object like:

selected: { key="", value=null }

It will make key and value observables, but not selected.

One other issue that you are having is that your first select specifies optionsValue: 'value'. This will cause it to write the value property of your object to selected instead of the object.

If you want to write the object itself, then you would want to completely remove the optionsValue binding.

Here is your fiddle with these updates: http://jsfiddle.net/rniemeyer/Dubu9/2/

like image 124
RP Niemeyer Avatar answered Feb 25 '23 23:02

RP Niemeyer