2011-10-03 79 views

回答

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); 
}; 
相关问题