knockout.js在按钮单击时从viewmodel1进行viewmodel2更改

时间:2017-04-04 11:08:53

标签: javascript asp.net-mvc knockout.js

这是我的代码

<h4>View Model 1 </h4>
<div data-bind="with: viewModel1">   
    <input data-bind="value: messageForVM2" />
    <button data-bind="click:abc">btn</button>
</div>

<h4>View Model 2</h4>
<div data-bind="with: viewModel2">
    <p data-bind="text:message">
    </p>

     <p data-bind="text:message2">
    </p>
</div>

这是viewmodel

var shouter = new ko.subscribable();    
var viewModel1 = function()
{   
    this.firstName = ko.observable("Wrapcode");
    this.messageForVM2 = ko.observable("Hello from first view model");
    this.messageForVM2.subscribe(function(newValue) {
        shouter.notifySubscribers(newValue, "messageToPublish");
    });
    this.message = ko.observable("Hello this is vm1");

    this.abc= function ()
    {
         alert("abc"); 
    };
};

var viewModel2 = function(vm1){
    this.message = ko.observable("Start typing message in input box above");
    shouter.subscribe(function(newValue) {
        this.message(newValue);
    }, this, "messageToPublish");
};


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

ko.applyBindings(masterVM)

我在viewmodel1中有一个按钮单击事件abc。如何通过点击viewmodel 1中的按钮来更改viewmodel2的message2。

1 个答案:

答案 0 :(得分:1)

首先,您需要首先在ViewModel2中提供message2对象。然后,您可以将父对象传递给child以获取对它的引用。

var viewModel1 = function(parentObject)
{   
  var self = this;
  self.parent = parentObject;
  ...
  ...
  this.abc = function () {
    self.parent.viewModel2.message2("Change the message from ViewModel1")
  };
};

var viewModel2 = function(vm1){
  this.message2 = ko.observable("");
  ...
};

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

ko.applyBindings(masterVM)

这是一个示例

   
function viewModel1(parentObject) {
  var self = this;
  self.parent = parentObject;
  self.total = ko.observable(0);
  self.clickAction = function() {
    self.total(self.total() + 1);
    self.parent.viewModel2.message(self.total() + "x modified from ViewModel1");
  };
} 
function viewModel2() {
  var self = this;
  self.message = ko.observable("Default message of ViewModel2");
}   
function viewModel() {
  var self = this;
  self.viewModel1 = new viewModel1(self);
  self.viewModel2 = new viewModel2();
}  
ko.applyBindings(new viewModel());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<div data-bind="with: viewModel1">
  <button data-bind="click:clickAction">Modify ViewModel2 message!</button>
</div>

<div data-bind="with: viewModel2">
  <div>Message:</div>
  <div data-bind="text: message"></div>
</div>