Craig Craig - 1 year ago 63
Javascript Question

Reading a count of a complex object in Knockout

I am trying to make a photo album site to learn. The screen I am working on now shows a list of albums. Each album has 0 to many photos attached.

In my knockout view model, I have:

self.Albums = ko.observableArray([]);

This is populated with a list of Album objects from my api call. Each album has a List of photos in them.

I make the call to get the albums:

var urialbums = '/api/Photo/GetAlbums';
$.get({ url: urialbums, contentType: "application/json" })
.done(function (data) {

data consist of a JSON object (I think?), which is a serialized version of this:

public class UIAlbumModel {
public int ID { get; set; }
public string Name { get; set; }
public string Description { get; set; }
public DateTime CreatedDate { get; set; }
public int PrivacyTypeID { get; set; }
public string PrivacyType { get; set; }
public List<UIPhotoModel> Photos { get; set; }

As you can see, it has a list of Photos.

A photo is an object with a name and a URL to the photo.

In my view, I am showing a list of the albums with the album name. However, next to the album name, I am trying to show the number of photos in the album.

<div data-bind="foreach: Albums">
<div class="col-xs-3">
<p><span data-bind="text: Name"></span> (<span data-bind="text: Photos().length"></span>)</p>
<span class="glyphicon glyphicon-folder-open"> </span>

But it's failing on the count of photos.

text: Photos().length


knockout-3.4.0.js:72 Uncaught TypeError: Unable to process binding
"text: function (){return Photos().length }" Message: Photos is not a

How can I get the number of child photos in the album that I'm currently foreach-ing through?

Answer Source

Change Photos().length to Photos.length. As the error message states, you are trying to invoke Photos as a function, but it isn't a function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download