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

标签 knockout.js

当我搜索时,我发现,如何将 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/

相关文章:

javascript - Knockout Js 计算出在模型中不起作用

javascript - 使用 html 绑定(bind)显示 ko.observable

javascript - 在自定义绑定(bind)中扩展可观察对象

javascript - 无容器控制流语法 - 模板无法使用 IE8 正确呈现

javascript - 多 View 模型破坏了 knockout.js

knockout.js - Knockout 可观察属性包含函数代码

javascript - knockout 嵌套组件 : $(document). Ready() ...在加载嵌套组件之前运行

javascript - Bootstrap 模态表单不会通过 knockout 的提交绑定(bind)提交

javascript - 编辑对象数组中新添加的项目并更新 DOM

drop-down-menu - knockout 选择属性 :{title Binding} not working as expected for Observable array