Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJS - Databind to a dictionary collection

Tags:

knockout.js

How do I use KnockoutJS to bind a dictionary collection to a select list.

If my "Destinations" dictionary looks like this in JSON:

{"Europe":"Europe incl Egypt, Turkey & Tunisia","ANZO":"Australia & New Zealand","WorldwideUSA":"Worldwide (incl USA & Canada)"}

How do I bind this to a select list. Something like this:

data_bind="value: Destination, options: Destinations.Value, optionsText: Destinations.Key"
like image 494
BrightonDev Avatar asked Sep 13 '11 10:09

BrightonDev


People also ask

What is text binding?

Text binding causes the associated DOM element to display the text value of the parameter. This is used in text-level DOM elements such as <span> or <em>. The text binding accepts any data type and parses it into String before rendering it.

How do you get the knockout value from observable?

To read the observable's current value, just call the observable with no parameters. In this example, myViewModel. personName() will return 'Bob' , and myViewModel. personAge() will return 123 .

What is Knockoutjs used for?

Knockout is a JavaScript library that helps you to create rich, responsive display and editor user interfaces with a clean underlying data model.

How do you bind data value?

The value binding links the associated DOM element's value with a property on your view model. This is typically useful with form elements such as <input> , <select> and <textarea> . When the user edits the value in the associated form control, it updates the value on your view model.


1 Answers

Typically, when dealing with a dictionary, you will want to map it to an array containing objects with key/value properties.

Would be something like:

function mapDictionaryToArray(dictionary) {
    var result = [];
    for (var key in dictionary) {
        if (dictionary.hasOwnProperty(key)) {
            result.push({ key: key, value: dictionary[key] }); 
        }  
    }

    return result;
}

Sample here: http://jsfiddle.net/rniemeyer/7yDTJ/

like image 60
RP Niemeyer Avatar answered Sep 29 '22 11:09

RP Niemeyer