从另一个视图模型观察KO observable

时间:2016-11-08 10:20:50

标签: javascript knockout.js durandal

所以我有两个视图模型相互接触

delete[] table;
var viewModel1 = function(){
    this.messageForVM2 = ko.observable("");
    this.message = ko.observable("Hello this is vm1")
};

var viewModel2 = function(vm1){
    this.message = ko.observable(vm1.messageForVM2());
};


var masterVM = (function(){
    this.viewModel1 =  new viewModel1(),
    this.viewModel2 = new viewModel2(this.viewModel1);
})();

ko.applyBindings(masterVM)

(也在这里map(_:)

我希望viewmodel2 data-bind只显示“hello”是viewmodel1中observable中的值。这有效但我希望它在viewmodel1输入中更新值时工作。

在我的例子中仅适用于:

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<h4>View Model 1</h4>
<div data-bind="with: viewModel1">
    <p data-bind="text: messageForVM2"></p>
    <input data-bind="value: messageForVM2, valueUpdate: 'input'" />
</div>

<h4>View Model 2</h4>
<div data-bind="with: viewModel2">
    <!-- ko if: message() === "hello" -->
    <p data-bind="text:message"></p>
    <!-- /ko -->
</div>

但需要删除如:

this.messageForVM2 = ko.observable("hello");

1 个答案:

答案 0 :(得分:2)

您需要将第一个viewmodel的Observable分配给第二个viewmodel的message变量。否则只会在第一次加载时设置。

变化:

this.message = ko.observable(vm1.messageForVM2());

要:

this.message = vm1.messageForVM2;

这样,this.message是对vm1.messageForVM2的引用,这意味着两个变量现在共享相同的值。

var viewModel1 = function(){
    this.messageForVM2 = ko.observable("");
    this.message = ko.observable("Hello this is vm1")
};

var viewModel2 = function(vm1){
    this.message = vm1.messageForVM2;
};


var masterVM = (function(){
    this.viewModel1 =  new viewModel1(),
    this.viewModel2 = new viewModel2(this.viewModel1);
})();

ko.applyBindings(masterVM)
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<h4>View Model 1</h4>
<div data-bind="with: viewModel1">
    <p data-bind="text: messageForVM2"></p>
    <input data-bind="value: messageForVM2, valueUpdate: 'input'" placeholder="Enter 'hello' here" />
</div>

<h4>View Model 2</h4>
<div data-bind="with: viewModel2">
    <!-- ko if: message() === "hello" -->
    <p data-bind="text:message"></p>
    <!-- /ko -->
</div>