【问题标题】:KnockoutJS multiple view models and 'breaking out' of oneKnockoutJS 多视图模型和“突破”一个
【发布时间】:2013-03-07 21:20:08
【问题描述】:

所以我正在使用 KnockoutJS 处理多个视图模型,如下所示:

function firstViewModel() {
    var self = this;
    self.dataArray = ko.observableArray([
        { title: "title1", theData: "data1" },
        { title: "title2", theData: "data2" },
        { title: "title3", theData: "data3" },
    ]);
};

function secondViewModel() {
    var self = this;
    self.addData = function() {
        firstViewModel.dataArray.push({ title: "newTitle", theData: "newData" });
        // trying to trigger dataArray in firstViewModel, doesn't work
    }
};

ko.applyBindings(new firstViewModel(), document.getElementById('first'));
ko.applyBindings(new secondViewModel(), document.getElementById('second'));

然后是这样的:

<div id="first" data-bind="with: dataArray">
    <ul data-bind="foreach: $data">
        <li data-bind="text: theData"></li>
    </ul>
</div>
<div id="second">
    <button data-bind="click: addData">add</button>
</div>

它的结构是这样的,因为我有一个第三视图模型,并且元素在 DOM 中重叠。我也不知道如何让this 工作。

有什么方法可以将 firstViewModel 的结构和引用保留在 secondViewModel 中? firstViewModel.theData.push("newData"); 显然不起作用,但我想我会包含它以进一步阐明我想要做什么。

我是 KO 的新手——如果这是个愚蠢的问题,我很抱歉。

编辑:看来我明白了!

如果我从 firstViewModel 中删除“self”,它会起作用...

dataArray = ko.observableArray([
    { title: "title1", theData: "data1" },
    { title: "title2", theData: "data2" }
]);

然后

self.addData = function() {
    dataArray.push({ title: "newTitle", theData: "newData" });
}

我还不知道删除“自我”是否会产生后果,但到目前为止它正在发挥作用。

【问题讨论】:

    标签: knockout.js viewmodel


    【解决方案1】:

    就我个人而言,我更喜欢让我的模型解耦,并使用发布/订阅模式让它们相互交流。查看我对Variable Dependency with knockoutJS的回复

    另外,如果你真的想走这条路,你也可以看看knockout postbox来完成同样的事情。

    【讨论】:

      【解决方案2】:

      您可以传递第一个视图模型的引用:

      function firstViewModel() {
          var self = this;
          self.dataArray = ko.observableArray([
              { title: "title1", theData: "data1" },
              { title: "title2", theData: "data2" },
              { title: "title3", theData: "data3" },
          ]);
      };
      
      function secondViewModel(firstViewModel) {
          var self = this;
          self.addData = function() {
              firstViewModel.dataArray.push({ title: "newTitle", theData: "newData" }); // doesn't work
          }
      };
      
      var firstVm = new firstViewModel();
      var secondVm = new secondViewModel(firstVm);
      ko.applyBindings(firstVm, document.getElementById('first'));
      ko.applyBindings(secondVm, document.getElementById('second'));
      

      【讨论】:

      • 感谢您查看。当我尝试时,'firstViewModel.dataArray 未定义'。
      猜你喜欢
      • 2014-05-08
      • 2012-12-24
      • 2015-10-31
      • 2014-04-03
      • 2019-01-23
      • 2014-06-24
      • 1970-01-01
      • 2015-07-19
      • 2013-03-22
      相关资源
      最近更新 更多