Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KnockoutJS binding to Key/Value pair

I am trying to bind to key/value pair data with KnockoutJS:

this.personal = {
  "name" : "Chuck",
  "country" : "USA"
};

In my HTML i use the $data binding:

<ul data-bind="foreach: personal">

  <li data-bind="text: $data"></li>

</ul>

which results in:

[object Object]

[object Object]

Does anybody know how my binding should look like if I want to see this:

name: Chuck

country: USA

in other words...how I can show the property name and the property value?

EDIT: Someone pointed me at: https://github.com/jamesfoster/knockout.observableDictionary But I still hope to bind without an extra library

like image 548
Loek Avatar asked Jun 15 '12 13:06

Loek


People also ask

What is KnockoutJS used for?

KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.

How do you activate a KnockoutJS model?

To activate Knockout, add the following line to a <script> block: ko. applyBindings(myViewModel); You can either put the script block at the bottom of your HTML document, or you can put it at the top and wrap the contents in a DOM-ready handler such as jQuery's $ function.

What is two-way binding in knockout JS?

KO is able to create a two-way binding if you use value to link a form element to an Observable property, so that the changes between them are exchanged among them. If you refer a simple property on ViewModel, KO will set the form element's initial state to property value.


1 Answers

There is an easier way of binding to a key-value pair using Knockout.js. Say you have a key value pair that looks like the following

myItems: [
            { Name: 'Item 1', Value: 1},
            { Name: 'Item 3', Value: 3},
            { Name: 'Item 4', Value: 4}
        ],

Just use the following html to bind to the key value pair.

<select data-bind="options: myItems, optionsText: 'Name', optionsValue: 'Value'></select>

References:

http://knockoutjs.com/documentation/options-binding.html

like image 174
aholtry Avatar answered Oct 05 '22 22:10

aholtry