如何在 Knockout 中 select 父视图模型?

How to select parent view model in Knockout?

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

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

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

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

为了简单起见,只需明确地将父项传递给子项。

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

function filterViewModel(parent) {
    // do whatever with the parent
    this.filter = function() {
        // ajax blablabla
    }
}

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

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" 可以是任何唯一字符串,用于标识您选择的模型的 属性。