I'm still reasonably new to KnockoutJS, I am having an issue with binding and cannot see what is wrong. I have tried various things but nothing seems to work. I'm sure there is probably a simple solution, I just can't see it!
I am calling data via ajax and trying to display one item from the data in the textbox, which then can be updated. I'm getting the following error in the console:
Uncaught ReferenceError: Unable to process binding "with: function (){return KHAViewModel }" Message: Unable to process binding "with: function (){return fundedWTEResults }" Message: Unable to process binding "textInput: function (){return ActualFundedWTE }" Message: ActualFundedWTE is not defined
Below is a cutdown version of my code and I have replicated my ajax script with some JS. I have also replicated it on jsFiddle:
HTML
<div class="container">
<pre data-bind="text: ko.toJSON($data, null, 2)"></pre>
</div>
<div class="container" id="dateSearch" >
<h2></h2>
<form class="form-inline" data-bind="with: KHAViewModel">
<div class="form-group" data-bind="with: fundedWTEResults">
<span>Funded WTE: </span>
<input id="fundedWTE" data-bind="textInput: ActualFundedWTE">
</div>
</form>
</div>
JS
// KHA View Model
function KHAViewModel() {
var self = this;
self.fundedWTEResults = ko.observableArray([]);
function fundedWTE (team) {
// $.ajax({
// url: "/...",
// type: "POST",
// ...........
// });
var r = [{"Team":team,"ActualFundedWTE":12.00}];
ko.mapping.fromJS(r, {}, self.fundedWTEResults);
}
fundedWTE('TeamA');
}
// Master View Model
function masterVM() {
var self = this;
self.KHAViewModel = new KHAViewModel();
};
// Activate Knockout
ko.applyBindings(new masterVM());
Thanks to @user3297291 pointing out the glaringly obvious problem.
The with:
binding that I used creates a new binding context, so that descendant elements are bound in the context of a specified object. So my array is still an object and therefore the objects inside the Array cannot by accessed in the desired way.
The correct binding to use is the foreach:
binding, the foreach binding duplicates a section of markup for each entry in an array, and binds each copy of that markup to the corresponding array item. Therefore allowing me to display the individual values within each object in the Array.
Also thanks to @Chris for sharing a great way to debug these kind of issues in the future using the ko.dataFor()
code.