如果一个页面上有多个视图模型,如何确保它们保持同步?例如,如果在一个视图模型上添加了一个项目或单击了一个按钮,而您希望另一个视图模式对该更改敏感,Knockout是否可以本地管理,或者最好使用一些消息传递或发布/子架构。
我想避免管理模型之间的可观察性。
Knockout 2.0确实包含了让您执行基本pub/sub的功能。下面是一个示例,其中两个视图模型通过中介进行通信。
var postbox = new ko.subscribable();
var ViewModelOne = function() {
this.items = ko.observableArray(["one", "two", "three"]);
this.selectedItem = ko.observable();
this.selectedItem.subscribe(function(newValue) {
postbox.notifySubscribers(newValue, "selected");
});
};
var ViewModelTwo = function() {
this.content = ko.observable();
postbox.subscribe(function(newValue) {
this.content(newValue + " content");
}, this, "selected");
};
ko.applyBindings(new ViewModelOne(), document.getElementById("choices"));
ko.applyBindings(new ViewModelTwo(), document.getElementById("content"));
第一视图模型通过邮箱通知特定主题,第二视图模型订阅该主题。他们彼此之间没有直接的依赖关系。
当然,邮箱不需要是全局的,可以传递到视图模型构造函数中,或者只在自执行函数中创建。
样品:http://jsfiddle.net/rniemeyer/z7KgM/
此外,postbox
可以只是ko.observable
(包括ko.subscribable
功能)。
你似乎正在朝着矛盾的目标前进。在Knockout中,你会这样做的方式是创建可观察性,但你似乎并不想要这样。
如果你有带可观察性的Foo和Bar对象,你可能不希望Foo上的可观察器与Bar或反之亦然,但为什么不有一个监视Foo和Bar并进行中介的Widget呢?
我为我最近的一个项目创建了一个小的扩展来解决这个问题。在方法上略有相似,但直接向已发布的可观察对象添加订阅,并且如果在发布可观察对象的声明之前声明,则会对订阅对象进行排队。
淘汰PubSub
我发现同步模型的方法是使用RP Niemeyer 的邮箱库
然而,我发现了一些关于observableArray的有趣之处。这就是为什么我创造了一个新的答案。只是为了完成Niemeyer的回答。
当使用postbox和observableArray时,在observaleArray中添加或删除元素时,会触发"subscribeTo"one_answers"publishOn"事件。更新数组中的元素时,它不会激发任何内容。我认为这与邮箱库无关,只是一个淘汰限制。
如果在更新可观察数组的元素时试图获取事件,最好使用邮箱库中的"publish"one_answers"subscribe"方法。
请参阅以下FIDDLE
代码参考:
function FundEntity (fund)
{
var self = this;
self.id = fund.id;
self.fundName = fund.fundName;
self.description = fund.description;
self.isFavorite = ko.observable(fund.isFavorite);
}
function GridViewModel(model) {
var self = this;
self.fundList = ko.observableArray();
model.funds.forEach(function(fund) {
self.fundList.push(new FundEntity(fund));
});
self.favorite = function (id, index) {
var newValue = {
id: id,
index: index,
isFavorite: self.fundList()[index].isFavorite()
};
ko.postbox.publish("itemChanged", newValue);
return true;
};
self.isEditable = ko.observable().subscribeTo("myEditableTopic");
}
function FundDetailViewModel(model) {
var self = this;
self.fundList = ko.observableArray();
model.funds.forEach(function(fund) {
self.fundList.push(new FundEntity(fund));
});
ko.postbox.subscribe("itemChanged", function (newValue) {
self.fundList()[newValue.index].isFavorite(newValue.isFavorite);
});
self.editable = ko.observable(false).publishOn("myEditableTopic");
}