I’m new in KnockoutJS, and I’m getting some problems.
I don’t understand why selectedOf isn’t updated after the click.
Can someone spot what I’m doing wrong?
<div>
<ul data-bind="foreach: Ofs">
<li data-bind="text: Number, click: $root.selectOf" style="cursor:pointer"/>
</ul>
<strong>Item clicked: </strong><span data-bind="text: selectedOf.Number" />
</div>
<script type"text/javascript">
var OfsModel = function (initialData) {
//console.log(initialData);
var self = this;
self.CurrentState = ko.observable(initialData.CurrentState);
self.Ofs = ko.observableArray(initialData.Ofs);
self.selectedOf = ko.observable();
self.selectOf = function (of) {
//console.log(of);
self.selectedOf(of);
//console.log(self.selectedOf());
}
}
var initialData = '{"Ofs":[{"Client":"A","Number":"1","Qty":10,"QtyRejected":5,"StopReason":"","ModifiedOn":"\/Date(1345732172456)\/","IsHighlighter":false,"SequencesAvailable":[{"Id":1,"Name":"Seq1"},{"Id":2,"Name":"Seq2"},{"Id":3,"Name":"Seq3"}],"SelectedSequence":null},{"Client":"B","Number":"2","Qty":20,"QtyRejected":0,"StopReason":"too much work","ModifiedOn":"\/Date(1345732172457)\/","IsHighlighter":false,"SequencesAvailable":[{"Id":1,"Name":"Seq1"},{"Id":2,"Name":"Seq2"}],"SelectedSequence":null},{"Client":"C","Number":"3","Qty":30,"QtyRejected":0,"StopReason":"","ModifiedOn":"\/Date(1345732172457)\/","IsHighlighter":false,"SequencesAvailable":[{"Id":1,"Name":"Seq1"}],"SelectedSequence":null}],"CurrentState":""}';
var vw = $.parseJSON(initialData);
ko.applyBindings(new OfsModel(vw));
</script>
EDIT:
I put the code on http://jsfiddle.net/muek/KBeZ3/2/
When you access the
Numberproperty off ofselectedOf, then you need to get to the value of the observable first by calling it as a function with no arguments likeselectedOf().Number.However, if you do this before
selectedOfis populated, then it will cause an error trying to accessNumberoff of an undefined value.A nice way around this is to use something like the
withbinding to set the scope for the children of an element. It also protects against null. This would look like:Here is a sample: http://jsfiddle.net/rniemeyer/ecDgD/
Alternatively you could create a computed observable for the
Numbervalue that protects against null or bind likedata-bind="text: selectedOf() ? selectedOf().Number : 'none'"