KnockoutJS订阅具有相同回调操作的多个observable [英] KnockoutJS subscribe to multiple observables with same callback action

查看:162
本文介绍了KnockoutJS订阅具有相同回调操作的多个observable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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 。这个想法是你使用一个在对象上调用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆