gpt4 book ai didi

knockout.js - 将值从一个 View 模型传递到 knockoutjs 中的另一个 View 模型

转载 作者:行者123 更新时间:2023-12-04 16:49:55 25 4
gpt4 key购买 nike

当我搜索时,我发现,如何将 View 模型的值绑定(bind)到 View 而不是 View 模型到 View 模型我需要将一个属性值从一个 View 模型传递到另一个 View 模型,因为我需要在第一个 View 模型中更新初始属性,然后我想在另一个 View 模型中使用它。因为它在测试时很有帮助。

假设下面的 View 模型是第一个 View 模型,

var xx = xx || {};
xx.yyy = xx.yyy || {};
xx.yyy.zzz = function(object ) {
var model = {};
model.isTested= ko.observable(false);

//below is the anonymous call to get the value(true/false):
datasource.someFeatureEnable.isTested().done(function (featureToggle) {
model.isTested(featureToggle.enabled);
});
}

我想在另一个 View 模型中传递 isTested(true/false) 属性值,因为要正确运行我的应用程序并使我的测试通过

最佳答案

您可以让您的第二个 View 模型依赖于您的第一个 View 模型。

//this is the definition of your first view model.
function MainViewModel(dataSource) {
var self = this;
this.DataSource = dataSource;
this.isTested = ko.observable(false);

//a callable function that will run isTested check on someFeatureEnable
this.TestSomeFeature = function() {
self.DataSource.someFeatureEnable.isTested().done(function (featureToggle) {
self.isTested(featureToggle.enabled);
});
};
return this;
}
//this is the definition of your second viewmodel
function SubViewModel(mainViewModel) {
var self = this;
self._mainViewModel = mainViewModel;
//for read only access
self.MainIsTested = function() { return self._mainViewModel.isTested(); }
//for read/write
self.MainIsTestedReference = self._mainViewModel.isTested
return self;
}



//this is the code that initializes the whole page.
var main = new MainViewModel();
var sub = new SubViewModel(main);
//now run the check
main.TestSomeFeature();

//these are examples, showing how to get at the isTested property in your various viewmodels. The comments are what the code should return
sub.MainIsTested(); //false
main.isTested(); //false
//set isTested to true from the sub
sub.MainIsTestedReference(true);
//now main isTested returns true, because the sub viewmodel and the main viewmodel have references to the same object.
main.isTested(); // true

如果您想获得更高级的知识并使用基于事件的方法,我建议您查看 ko.postbox,查看这些引用资料。

http://www.knockmeout.net/2012/05/using-ko-native-pubsub.html

https://github.com/rniemeyer/knockout-postbox

关于knockout.js - 将值从一个 View 模型传递到 knockoutjs 中的另一个 View 模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22134386/

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