开发者

changing property from another viewmodel

开发者 https://www.devze.com 2023-04-10 12:27 出处:网络
Im trying to \"connect\" two开发者_开发技巧 viewModels, clicking a button in one, to trigger/change observable in another viewmodel.

Im trying to "connect" two开发者_开发技巧 viewModels, clicking a button in one, to trigger/change observable in another viewmodel.

knockout v 1.3

something like this: http://jsfiddle.net/ffBDr/9/

thanks


I think that you could choose to explicitly indicate which model to communicate with like: 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;
};

or you could use subscriptions like: 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);
};
0

精彩评论

暂无评论...
验证码 换一张
取 消