I\'ve a super simple knockout code below:
var data ={
\"Id\" : 1001,
\"SalePrice\" : 12345,
\"ListPrice\" : 333,
\"ShortDesc\" : \"Tayler 123
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>
If the page is read only, and the view model will not change, (as in my case) then you don't need the observable.
You can also make the code sample work by doing this:
var viewModel={
dataTest: data
};
Then you can access your properties in the data binding with simple dot notation.
<span data-bind="text: dataTest.SalePrice"></span>
Using a context or with binding was not desirable in my case since I would have to continually switch back and forth between 2 objects in a comparison table.
Call to ko.observable needs to be moved from MVVM to HTML element:
var data ={
"Id" : 1001,
"SalePrice" : 12345,
"ListPrice" : 333,
"ShortDesc" : "Tayler 12345E",
"Description" : " Long Description"
};
var viewModel={
dataTest: data
};
ko.applyBindings(viewModel);
<span data-bind="text: ko.observable(dataTest.SalePrice)"></span>
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.
It can be also written as:
<span data-bind="text: dataTest()['SalePrice']"></span>