Unable to link process
I am currently trying to create a list of people with this model
{firstName: "", lastname: "", address:""}
in multiple values ββSelect.
In my ViewModel I have a field called selectedItem and I am setting it to null because nothing is selected to start with.
In my opinion, I can set the selectedItem to the item that was selected in my Select item, then I want to display the properties of the selected item on the screen, as I tried this,
<p data-bind="text: selectedItem.firstName">First Name</p>
<p data-bind="text: selectedItem.lastName">Last Name</p>
<p data-bind="text: selectedItem.address">Address</p>
but he talks about it in the console
Unable to process binding "text: function (){return selectedItem.firstName }"
Message: Cannot read property 'firstName' of undefined;
which stops all other bindings (I have a delete button next). The console message seems to indicate that the viewModel is being processed after the page has been or something, otherwise it will complain about null values ββto the right ??? Is there anyway for the binding to be ignored if the selected item is undefined / null or am I trying to get it wrong?
Edit: here's a jsFiddle , but I noticed that it doesn't behave 100% the same as it does in a node-webkit environment. I am using, it gets all the data of the first item in the list, but then it does nothing
source to share
First you need to make the selectedItem
observable to be notified when it changes:
self.selectedItem = ko.observable(null);
Then you need to handle the case when selectedItem
empty in your bindings with:
<div class="col-md-8">
<p data-bind="text: selectedItem() && selectedItem().firstName">First Name</p>
<p data-bind="text: selectedItem() && selectedItem().lastName">Last Name</p>
<p data-bind="text: selectedItem() && selectedItem().address">Address</p>
</div>
However, a more correct solution would be to use a binding with
that takes care of the case when selectedItem
null
and also reduces repetition:
<div class="col-md-8" data-bind="with: selectedItem">
<p data-bind="text: firstName">First Name</p>
<p data-bind="text: lastName">Last Name</p>
<p data-bind="text: address">Address</p>
</div>
Demo JSFiddle .
source to share