I'm trying to bind some dynamic values to a div but for some reason the div doesn't fetch the data properly.
This is what I have:
HTML:
<div class="section-content tabcontent sc7" id="gridEventLimits" style="padding: 0; background-color: #fff; display: none">
<div style="clear: both">
</div>
<table>
<tr>
<td></td>
<td></td>
<td colspan="4"></td>
</tr>
<tr>
<table class="sgrid" data-bind="visible: skills && skills.length > 0"
style="width: 100%; border-collapse: collapse; border: solid 1px #aaa">
<thead>
<tr style="background: rgb(242, 242, 225); color: #333">
<td>Event Skills
</td>
</tr>
</thead>
<tbody data-bind="foreach: skills">
<tr>
<td>
<ul class="collapsible" data-bind="attr: { id: 'collapsible' + Id }">
<li><span data-bind="text: Name" style="color: #365474"></span>
</li>
</ul>
</td>
</tr>
</tbody>
</table>
<p data-bind="visible: !skills || skills.length == 0" style="text-align: center">
-- No People Found --
</p>
</tr>
</table>
</div>
Then I have js function which is called on page load event:
var skillPeopleList;
function ApplyKOBindingsToSkillPeopleDetails() {
if (eventId > 0) {
var element = $('#gridEventLimits')[0];
skillPeopleList = new SkillPeopleListModel(eventId);
ko.applyBindings(skillPeopleList, element);
}
}
function SkillPeopleListModel(id) {
var self = this;
self.Id = id;
self.skills = ko.observableArray([]);
//initialize
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/webservices/EventScheduleService.asmx/GetEventSkills",
data: "{'eventId':" + self.Id + "}",
dataType: "json",
async: true,
success: function (data) {
result = data.d;
if (result) {
//if (result.skills) {
// result.skills.forEach(function (entry) {
result.forEach(function (entry) {
self.skills.push(entry);
});
//}
}
},
error: function (data, status, error) {
}
});
}
The content of the web service response (result object) is this one:
Any idea what am I doing wrong? I'm new with Knockoutjs and I'm still learning the framework.
Changing the bindings to
skills && skills().length > 0
And
!skills() || skills().length == 0
Will fix it. Skills is an observableArray, so skills.length will cause an error and break the other bindings. Unwrapping the observable and then checking length will fix it.
As a side note, this kind of logic would be better placed inside the view-model, so you can keep your model-view and view-model separate.