2
votes

I’m trying to update a computed knockout value using ko.compute on my current productsList observableArray and my "imageUrl". I keep getting undefined or ImageGalleryId is not a function when I try to get the value.

var productModel = function () {
    var self = this;
    window.viewModel = self;

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

    // I would like to get the image url for the current product
    self.productsList.ImageUrl = ko.computed(function () {

         // returns undefined
         // var imageId = self.productsList.ImageGalleryId;

         // returns: self.productsList.ImageGalleryId is not a function
         // var imageId = self.productsList.ImageGalleryId();

         // Need help **here**
         var imageId = self.productsList.ImageGalleryId();

         var imagePath = "/Image/GetImage/";
         var imageSize = "/175/175/";
         var url = imagePath + imageId + imageSize;
         //console.log(url);
         return url;

    },self); // end ImageUrl

    // Load data when model is created
    self.dummyCompute = ko.computed(function () {
         // start dummyCompute

         //ajax call omitted 
         var JSONdataFromServer = {
           "productsList":[
              {
                 "ProductId":1,
                 "Title":"Product Name",
                 "ImageGalleryId":10,
                                     "ImageUrl":"http://example.com"
              },
                              {
                 "ProductId":2,
                 "Title":"Product Name",
                 "ImageGalleryId":11,
                                     "ImageUrl":"http://example.com"
              }
           ]};

         self.productsList(JSONdataFromServer.productsList);

         }, self); // end dummyCompute

    };

ko.applyBindings(new productModel());

Fiddle code: http://jsfiddle.net/Y8yT6/2/

1

1 Answers

0
votes

productsList is an array, but you're treating it as if it were an object. I assume that you're really trying to deal with the properties of some specific member of the array, but there's nothing in your computed that tells it which one is the "current" product.

Once you get that resolved, you want ProductId without any parentheses, since it's a plain value and not an observable.