knockout viewModel ko.computed value not a function

时间:2013-12-04 20:05:10

标签: asp.net-mvc razor knockout.js

我正在尝试使用当前productsList observableArray和我的“imageUrl”上的ko.compute更新计算出的挖空值。当我试图获取值时,我一直未定义或ImageGalleryId不是函数。

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());

小提琴代码: http://jsfiddle.net/Y8yT6/2/

1 个答案:

答案 0 :(得分:0)

productsList是一个数组,但您将它视为一个对象。我假设您真的试图处理数组中某个特定成员的属性,但是computed中没有任何内容告诉它哪一个是“当前”产品。

一旦解决了问题,您希望ProductId没有任何括号,因为它是一个普通值,而不是observable