问题描述
我需要使用一些存储在用户 Meteor.user()
对象中的子属性,例如 Meteor.user().profile.preferences.preference_one
,Meteor.user().profile.preferences.preference_two
等等.这些子属性被用在反应式自动运行块中,因为在它们发生变化时必须进行重新计算.
I need to use some subproperties which are stored in the user's Meteor.user()
object, such as Meteor.user().profile.preferences.preference_one
, Meteor.user().profile.preferences.preference_two
, et cetera. These subproperties are being used inside reactive autorun blocks because there are recalculations that must be done anytime they change.
我发现当我从一个反应块中引用这些子属性的值时,自动运行会被触发以任何对Meteor.user()的更改代码> 对象,包括不会以任何方式影响我明确引用的数据的更改.例如,如果
Meteor.user().profile.name
已更新,则任何包含 Meteor.user().profile.preferences.preference_one
或 的自动运行Meteor.user().profile.preferences.preference_two
也会被触发,因为它们都有一个共同的父级.
I've discovered that when I refer to the value of these subproperties from within a reactive block, then the autorun is fired for any change to the Meteor.user()
object, including changes which do not affect in any way the data that I am explicitly referencing. For example, if Meteor.user().profile.name
is updated, then any autorun that includes Meteor.user().profile.preferences.preference_one
or Meteor.user().profile.preferences.preference_two
gets fired as well, because they all have a common parent.
我看过一个类似的问题 处理限制 Meteor 反应性的范围,但它处理自定义集合,而不是 Meteor.users
集合.我看不到那里的解决方案如何适用,因为他们在订阅中指定字段以限制发布到客户端的子属性,在我的情况下,我需要 Meteor.user()
.但我需要能够选择我对哪些子属性做出反应!
I have seen a similar question dealing with limiting the scope of Meteor's reactivity, but it deals with a custom collection, not the Meteor.users
collection. I cannot see how the solution there could be made applicable because they are specifying fields in subscriptions to limit what subproperties are published to the client, and in my case, I need all the subproperties of Meteor.user()
. But I need to be able to choose which subproperties I am reacting to!
在本地存储子属性值,然后比较每个更改当然可以工作,但这是一个蛮力解决方案,因为它需要额外的逻辑并且自动运行无论如何都会被触发.
Storing subproperty values locally and then comparing on every change would of course work, but it is a brute force solution solution in that it requires extra logic and that the autoruns will all be firing anyway.
推荐答案
我不知道这是否是最佳方式,但看看这个例子:
I don't know if this is the best way, but have a look at this example:
Tracker.autorun(function() {
var user = Meteor.user();
if (user && user.profile)
Session.set('p1', user.profile.preference1);
});
Tracker.autorun(function() {
var p1 = Session.get('p1');
console.log("p1 is " + p1);
});
第一个 autorun
将在每次用户数据更改时触发,但是第二个 autorun
仅在特定属性更改时触发.
The first autorun
will fire every time the user data changes, however the second autorun
will fire only when that particular property changes.
这篇关于使 Meteor 对 Meteor.user() 的特定子项具有反应性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!