如何使用knockoutjs过滤父视图模型的子视图模型? [英] How to use knockoutjs to filter child viewmodels of a parent viewmodel?

查看:86
本文介绍了如何使用knockoutjs过滤父视图模型的子视图模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个viewmodel,它从MVC控制器获取数据并在视图中转换为JSON。数据由两个列表(PlayList和TeamMembers)组成。我使用Knockout Mapping使数据可观察。



我想为每个子viewModel(playListItems和teamMemberItems)创建一个名为'getSelected'的函数,并且能够调用视图中的方法。但是,我的尝试似乎返回整个父视图模型,而不是过滤后的子视图模型。



任何帮助 感谢。



我尝试过:



I have a viewmodel that gets its data from a MVC controller and is converted to JSON in the view. The data is comprised of two lists (PlayList and TeamMembers). I use Knockout Mapping make the data observable.

I would like to create a function called 'getSelected' for each child viewModel (playListItems and teamMemberItems) and be able to call the method from within the view. However, my attempt seems to return the entire parent viewmodel and not the filtered child viewmodel.

Any help would be appreciated.

What I have tried:

var ViewModel = function(data) {
        var self = this;
        self.playListItems = data.PlayList;
        self.teamMemberItems = data.TeamMembers;

        self.playListItems.getSelected = ko.observable(function(id) {
            var currentItem = ko.utils.arrayFirst(self.playListItems(),
                function(item) {
                    return item.RecordingId() === id;
                }).item;

            return currentItem;
        });
    }

推荐答案

我能够通过在语法中添加'._latestValue'来实现这一点..我是不确定它是否是'正确'的方式。



I was able to get this to work by adding '._latestValue' to the syntax.. I am not sure if it the 'correct' way to do it.

self.playListItems.getSelected = function(id) {
    var currentItem = ko.utils.arrayFirst(self.playListItems._latestValue,
        function(item) {
            return item.RecordingId() === id;
        });

    return currentItem;
};


这篇关于如何使用knockoutjs过滤父视图模型的子视图模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆