【问题标题】:Observable object vs ObservableArray and arrayFilterObservable 对象 vs ObservableArray 和 arrayFilter
【发布时间】:2016-03-18 11:28:00
【问题描述】:

我正在通过 ko.mapping.fromJS(data, {}, this); 将列表映射到 observablearray 的 json 数据;

当页面加载时,数组中的第一项通过以下代码设置为选中。当用户单击缩略图时,我将通过 ajax 抓取该图像/照片并将其放入图像 observableArray 中。这里的目标是在本地存储用户单击时选择的每张照片,当他们再次单击该图像时,它首先检查 observablearray 以查看是否已加载

ko.mapping.fromJS(data, {}, this);
    

//set self.selected value to the first item in the array
self.selected = ko.observable(self.photos()[0]);

//initializing in page observableArray
self.images = ko.observableArray([]);

//putting already loaded first item into images
self.images.push(self.photos()[0]);

当用户单击缩略图时,我执行以下操作以查看图像是否在可观察数组中。如果未找到,则执行 ajax 从服务器获取,否则只需将所选照片设置为新的 self.selected

//in array
var found = ko.utils.arrayFilter(self.images(), function (item) {
    return item.photoId() == id;
});
if (found.length === 0) {

  var q = ko.mapping.toJSON({ id: id });
  GetData(url + '/GetPhotoClient', q,
   function (data) {
      if (data.success === true) {

      ko.mapping.fromJS(data.photoClient, {}, self.selected);
      self.selected(data.photoClient);
    
      //put recent photo into images
      self.images.push(ph);

  } else {
    alert(data.success);
  }
}
        , true);
} else {
    self.selected(ko.observable(found));
}

在我用来显示图像的页面中。

困惑/问题是有时我没有使用 selected().imageSource 和其他时候 selected.imageSource。

find 的值似乎是一个 object not 和 observable object。我相信我在这里遗漏了一些基本概念。即为什么有时我使用 selected().imageSource 而其他时候它是 selected.imageSource 以及为什么对象的值等于对象而不是可观察对象。

我希望这很清楚。

【问题讨论】:

    标签: knockout.js knockout-mapping-plugin observable


    【解决方案1】:

    发生这种情况是因为当您从服务器获取客户端照片时,您不会为该对象 self.selected(data.photoClient); 创建一个可观察对象,而当您已经拥有照片时,您会为找到的对象 self.selected(ko.observable(found)); 创建一个可观察对象。

    顺便说一句,你可能应该看看 ko.utils.unwrapObservable(obj),它抽象了 observable 概念并总是返回对象的值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-14
      • 1970-01-01
      • 2016-09-10
      相关资源
      最近更新 更多