I have an observable array of items in which each item has a collection of images (example below):
{"itemImages":[{"id":4,"itemId":9,"itemImageUrl":"$_57.JPG","createdOn":"2015-02-25T21:41:38.193","modifiedOn":"2015-02-25T21:41:38.193"}],"id":9,"itemName":"Item 1","itemDescription":"Item 1","itemPrice":5.00,"itemQuantity":1,"itemInStock":1,"createdOn":"2015-02-25T21:41:38.193","modifiedOn":"2015-02-25T21:41:38.193"}
OR the below JSON when no image available:
{"itemImages":[],"id":9,"itemName":"Item 1","itemDescription":"Item 1","itemPrice":5.00,"itemQuantity":1,"itemInStock":1,"createdOn":"2015-02-25T21:41:38.193","modifiedOn":"2015-02-25T21:41:38.193"}
The issue I am having is that the Image collection is not always populated and in these instances, I am getting the error:
Uncaught TypeError: Cannot read property 'itemImages' of undefined
I get that the error is saying the collection is undefined and have been trying to handle this by setting the image to a 'no-image' image in these cases. Even with this check, the error is still being thrown which implies I am writing the computed observable logic incorrectly.
@section scripts {
<script>
$(function () {
var ViewModel = function () {
var self = this;
self.items = ko.observableArray(@Html.Raw(Model.ItemsJSON));
};
var vm = new ViewModel();
// Iterates over each item.
_.each(vm.items(), function (item) {
var self = this;
item.imageUrl = ko.computed(function () {
if (item.itemImages[0].length == 0)
{ var fileName = 'no-image-jpg' }
else { fileName = item.itemImage[0].itemImageUrl }
var url = '@Model.ImageUrlPrefix' + fileName
return url;
});
//End Foreach loop.
});
ko.applyBindings(vm);
And then for the Html, I am iterating over the item observable array on the viewmodel.
<div id="list-container" class="row">
<div data-bind="template: { name: 'list-template', foreach: items }"></div>
</div>
<script type="text/html" id="list-template">
<div>
<div>
<div>
<img data-bind="attr: { src: imageUrl }"/>
</div>
...
Would appreciate if anyone could point out why my computed observable is not catching undefined collections and setting the fileName to 'no-image.jpg' for them.