gpt4 book ai didi

javascript - 如何在 Knockout 中选择父 View 模型?

转载 作者:行者123 更新时间:2023-11-30 09:59:53 24 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

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

关于javascript - 如何在 Knockout 中选择父 View 模型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32209865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com