Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js how to access the inner object property on data-bind

Tags:

I've a super simple knockout code below:

var data ={     "Id" : 1001,     "SalePrice" : 12345,     "ListPrice" : 333,     "ShortDesc" : "Tayler 12345E",     "Description" : " Long Description" };   var viewModel={     dataTest: ko.observable(data) };   ko.applyBindings(viewModel);  <span data-bind="text: dataTest.SalePrice"></span> 

Basically, I've passed the whole data object to observable property dataTest. I would have thought it's easy enough to access the property of inner object with dot notation. But's not.

Could someone please help how to make above code to work?

like image 574
Nil Pun Avatar asked Jun 02 '13 03:06

Nil Pun


People also ask

What is data bind Knockout?

Knockout's declarative binding system provides a concise and powerful way to link data to the UI. It's generally easy and obvious to bind to simple data properties or to use a single binding.

What is two-way binding in KnockoutJS?

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.

What is data bind in JavaScript?

Data binding in concept is quite simple. On one side, you have a data model and on the other side, you have an interface, often called a view. The idea is that you want to “bind” some piece of data to something on the view so that when the data changes, the view changes.


2 Answers

It's an observable now (ie, it's a function). You need to call the function.

<span data-bind="text: dataTest().SalePrice"></span> 

Editing Akshat's fiddle to match.

Not sure why this is an advantage over nesting a proper hierarchy, however. What the OP is asking is pretty anti-pattern. I think you might want to look over the page on binding context Akshat suggests to see how to create the dataTest as a parent object and then drill down in your markup.

like image 72
ruffin Avatar answered Oct 23 '22 22:10

ruffin


Check out the fiddle.All you need to do is this

<span data-bind="text: salePrice "></span> 

This will populate the span element with sale price defined in the view model.

From your question it appears to me that what you are trying to do is bind the view model to different elements of the html page. To achieve this you can pass an id parameter to the apply bindings to bind a specific view model to a specific section of the page. Like this

ko.applyBindings(viewmodel,document.getElementById('id'));  

If you are looking to directly access the view model use the binding context. In this case you need the $data binding context.So the binding in span will change to

<span data-bind="text:$data.salePrice"></span> 
like image 30
Akshat Jiwan Sharma Avatar answered Oct 23 '22 22:10

Akshat Jiwan Sharma