答案 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);
};