【问题标题】:Instantiate ViewModel from array items within an existing ViewModel.从现有 ViewModel 中的数组项实例化 ViewModel。
【发布时间】:2016-01-08 01:58:52
【问题描述】:

我刚刚开始搞乱淘汰赛(技术要求),我正在尝试建立一个具有一些自定义功能的画廊。

数据来自代表一个画廊(标题、描述等)的json 响应,在画廊对象中,是一组幻灯片。

为了尝试分离关注点,我希望有一个基于画廊的 ViewModel 和一个单独的幻灯片 ViewModel。

但我不确定如何在对象内的数组上实例化幻灯片 ViewModel。

在早期版本中,我尝试循环遍历幻灯片数组,但不确定如何物理执行我正在尝试执行的操作,即在 @ 中的每个 slide 对象上设置 SlideViewModel 的新实例987654324@数组

感谢任何帮助。在这里写代码:http://codepen.io/pbj/pen/MaoLMb

代码在这里:

JS

var testGallery = {
  "title" : "Anna's Gallery Title",
  "slides" : [
    {
      "title": "Slide Image #1",
      "image" : "http://google.com/image/goes/here"
    },
    {
      "title": "Slide Image #1",
      "image" : "http://google.com/image/goes/here"
    },
    {
      "title": "Slide Image #1",
      "image" : "http://google.com/image/goes/here"
    },
    {
      "title": "Slide Image #1",
      "image" : "http://google.com/image/goes/here"
    },
  ]
}

function GalleryViewModel(data) {
  // gallery functions
  this.title = ko.observable(data.title);
}

function SlideViewModel() {
 // slide functions here
 this.name = ko.observable(data.slides.title);
}

var gallery = new GalleryViewModel(testGallery);

ko.applyBindings(gallery);

【问题讨论】:

    标签: javascript arrays mvvm knockout.js


    【解决方案1】:

    您应该创建slide 的子函数来实现您正在查看的内容。

    视图模型:

     function GalleryViewModel(data) {
            var self = this;
            self.title = ko.observable(data.title);
            self.caption = ko.observable(data.caption);
            self.slides = ko.observableArray();
            self.totalSlides = ko.observable(data.totalSlides);
    
            self.slides($.map(data.slides, function (n) { //mapping my child function in here
                return new slide(n);
            }))
        }
    
        function slide(data) { //child function
            this.title = ko.observable(data.title);
            this.image = ko.observable(data.image);
            this.position = ko.observable(data.position);
        }
    
    var gallery = new GalleryViewModel(annasGallery);
    ko.applyBindings(gallery);
    

    工作样本 here 供抢购

    您可以寻求 mapping plugin 的帮助,这将是在单行中执行此操作的另一种方式(根据您的代码)

    代码:

    ko.applyBindings(ko.mapping.fromJS(annasGallery));
    

    使用映射插件检查示例here

    PS:据我所知,没有什么是可编辑的,您可以将平面 js 数组绑定到视图(不必要地使用 observable 会变得昂贵)

    【讨论】:

    • 这太好了,谢谢!大多数事情都是可观察的部分原因是因为这最终会在以后做两件事:1. 将新幻灯片添加到现有画廊。 2.无缝集成新图库(拼接效果)。所以幻灯片需要是可观察的。
    • @patrick 考虑关闭这个问题,将其标记为答案并投票赞成。干杯
    猜你喜欢
    • 2020-05-19
    • 1970-01-01
    • 2020-04-10
    • 1970-01-01
    • 2020-11-16
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    • 2023-04-03
    相关资源
    最近更新 更多