When I call the length of any observable customerOverview view in the model, I get zero. There is data in the observed data, like updating data bindings, however the length remains equal to 0. The CustomerCentral base view model returns the lengths properly. I need the length of some observables in "CustomerOverview" to execute some conditional statements.
HTML bindings
<ul class="nav nav-list"> <li class="nav-header">Contacts</li> <li>No contacts associated with this customer</li> <li> <a data-bind="click: $root.customerOverview.viewContact"><i class="icon-chevron- right single pull-right"> </i><span data-bind="text: FirstName"></span><span data-bind="text: LastName"></span> </a></li> </ul>
Js
function CustomerOverview() { var self = this; self.contacts = ko.observableArray([]); self.getCustomerContacts = function () { requestController = "/CRM/CustomerCentral/CustomerContacts"; queryString = "?id=" + self.customer().Id(); $.ajax({ cache: false, type: "GET", dataType: "json", url: baseURL + requestController + queryString, headers: { "AuthToken": cookie }, success: function (data) { if (data.data.length > 0) { self.contacts(ko.mapping.fromJS(data.data)); console.log(self.contacts().length); } } }); }; }; function CustomerCentral() { var self = this; self.customerOverview = ko.observable(new customerOverview()); }; var vm = new CustomerCentral(); ko.applyBindings(vm);
Cmd console: vm.customerOverview (). contacts (). length 0
--------------------------- DECISION ------------------- --- observableArray.push ()
The problem turned out to be this:
self.contacts(ko.mapping.fromJS(data.data));
SOLUTION: Adding .push () to this allowed us to increase the value of the length property of the array. I assumed that ko.mapping will handle this, but it is not. The change in the variable did not affect the observed.
$.each(data.data, function () { self.contacts.push(ko.mapping.fromJS(this)); console.log(self.contacts().length); });
Strake
source share