【问题标题】:How to select parent view model in Knockout?如何在 Knockout 中选择父视图模型?
【发布时间】:2015-11-19 12:05:19
【问题描述】:

我在我的页面中使用了两个视图模型mainViewModelfilterViewModel,其中filterViewModelmainViewModel 实例化

function mainViewModel() {
    this.data   = ko.observableArray();
    this.filter = new filterViewModel();
}

function filterViewModel() {
    this.filter = function() {
        // ajax blablabla
    }
}

如何从filterViewModel 访问我的mainViewModel 以设置由filterViewModel 执行的ajax 结果,到您的父视图模型中的data 变量?

【问题讨论】:

    标签: javascript knockout.js viewmodel


    【解决方案1】:

    为简单起见,只需将父级显式传递给子级即可。

    function mainViewModel() {
        this.data   = ko.observableArray();
        this.filter = new filterViewModel(this);
    }
    
    function filterViewModel(parent) {
        // do whatever with the parent
        this.filter = function() {
            // ajax blablabla
        }
    }
    

    正如 cmets 指出的那样,这会引入不必要的依赖。所以最好传递你要使用的属性而不是父模型。

    function mainViewModel() {
        this.data   = ko.observableArray();
        this.filter = new filterViewModel(this.data);
    }
    
    function filterViewModel(data) {
        // do whatever with the data
        this.filter = function() {
            // ajax blablabla
        }
    }
    

    或者你可以使用一个很棒的淘汰赛插件knockout-postbox

    function mainViewModel() {
        this.data = ko.observableArray()
             .syncWith('parentData');
        this.filter = new filterViewModel();
    }
    
    function filterViewModel() {
        this.parentData = ko.observableArray()
            .syncWith('parentData');
    
        this.filter = function() {
            // ajax blablabla
            // do whatever with this.parentData
        }
    }
    

    请注意,“parentData”可以是标识您选择的模型属性的任何唯一字符串。

    【讨论】:

    • 太棒了!这可以解决我的问题,但是对于这种情况,Knockout 默认没有任何办法?
    • 我不知道。此时它是纯 JS,因此您无能为力(您可以查找调用者,但这是一种不好的做法)。另一方面,在标记中,剔除允许通过 $parent 引用访问父模型。
    • 我建议不要使用$parent 来访问不同的视图模型。它极大地限制了您使用子视图模型的方式和位置。
    • 通常将父级传递给子级是多余的,并且会产生不必要的依赖。只从父级传递子级需要的回调和可观察对象会更简洁。
    • 好电话@CrimsonChris!我已经更新了答案。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2013-09-16
    • 1970-01-01
    • 2013-01-03
    • 1970-01-01
    • 2017-04-11
    • 2013-08-28
    • 1970-01-01
    • 2016-02-13
    相关资源
    最近更新 更多