从另一个视图模型更改属性

时间:2011-10-03 12:59:19

标签: knockout.js

我试图“连接”两个viewModel, 单击一个按钮,在另一个视图模型中触发/更改observable。

淘汰赛1.3

这样的事情: http://jsfiddle.net/ffBDr/9/

感谢

1 个答案:

答案 0 :(得分:3)

我认为您可以选择明确指出要与之沟通的模型:http://jsfiddle.net/CG5LW/

function BoxA() {
   this.Imlistening=ko.observable('');
   this.tellThem = function(){
       if (this.whoToTell) {
          this.whoToTell.Imlistening("message from A");
       }   
   };
}

function BoxB() {
   this.Imlistening=ko.observable('');
    this.tellThem = function(){
        if (this.whoToTell) {
           this.whoToTell.Imlistening("message from B");   
        }
    }; 
}

function appViewModel() {
    this.BoxA = new BoxA();
    this.BoxB = new BoxB();
    this.BoxA.whoToTell = this.BoxB;
    this.BoxB.whoToTell = this.BoxA;
};

或者您可以使用以下订阅:http://jsfiddle.net/CG5LW/1/

function BoxA() {
   this.Imlistening=ko.observable('');
   this.message = ko.observable('');

   this.tellThem = function(){
       this.message("message from A");  
   };
}

function BoxB() {
   this.Imlistening=ko.observable('');
   this.message = ko.observable('');

   this.tellThem = function(){
        this.message("message from B");
    }; 
}

function appViewModel() {
    this.BoxA = new BoxA();
    this.BoxB = new BoxB();

    function receiveMessage(newValue) {
       this.Imlistening(newValue);   
    }

    this.BoxA.message.subscribe(receiveMessage, this.BoxB);
    this.BoxB.message.subscribe(receiveMessage, this.BoxA);
};