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
KnockoutJS is basically a library written in JavaScript, based on MVVM pattern that helps developers build rich and responsive websites.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With