KnockoutJS 使用相同的回调操作订阅多个 observable [英] KnockoutJS subscribe to multiple observables with same callback action
问题描述
我在 KnockoutJS 中有一个模型类,它有多个我想订阅的值.每个订阅都将执行相同的任务,如下所示:
I've got a model class in KnockoutJS which has multiple values that I'd like to subscribe to. Each subscription will perform the same task, like so:
function CaseAssignmentZipCode(zipCode, userId, isNew) {
var self = this;
self.zipCode = ko.observable(zipCode);
self.userId = ko.observable(userId);
self.isNew = isNew;
self.isUpdated = false;
self.zipCode.subscribe(function () { self.isUpdated = true; });
self.userId.subscribe(function () { self.isUpdated = true; });
}
有没有办法将这两个调用结合起来进行订阅,以便我可以使用一个订阅来观察"这两个值?
Is there a way to combine these two calls to subscribe, so that I can use one subscription to 'watch' both values?
推荐答案
您可以为此目的使用计算的 observable.您只需要确保在 read 函数中访问每个 observable 的值.会是这样的:
You can use a computed observable for this purpose. You just need to make sure that you access the value of each observable in the read function. Would be something like:
ko.computed(function() {
self.zipCode();
self.userId();
self.isUpdated = true;
});
因此,您获得了对两个 observable 的依赖并设置了您的标志.
So, you get dependencies on the two observables and set your flag.
此外,如果您正在寻找诸如脏"标志之类的东西,那么您可以考虑以下内容:http://www.knockmeout.net/2011/05/creating-smart-dirty-flag-in-knockoutjs.html.这个想法是你使用一个计算的 observable,它在一个对象上调用 ko.toJS() 来解开它的所有 observable.
Also, if you are looking for something like a "dirty" flag, then you might consider something like: http://www.knockmeout.net/2011/05/creating-smart-dirty-flag-in-knockoutjs.html. The idea is that you use a computed observable that calls ko.toJS() on an object to unwrap all of its observables.
这篇关于KnockoutJS 使用相同的回调操作订阅多个 observable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!