【发布时间】:2014-11-19 08:03:38
【问题描述】:
我遇到了一个问题,Meteor 订阅在刷新后未将复选框设置为“选中”。基本上,如果我运行 Meteor 并更改 JS,应用程序将按预期工作(从 Meteor.user() 提取数据并相应地设置复选框)。但是,如果我刷新应用程序,我的所有复选框都设置为 false。我不明白为什么会发生这种情况,有什么想法吗?
我的订阅如下:
服务器端
Meteor.publish("user-preferences", function () {
if (this.userId) {
return Meteor.users.find({_id: this.userId},
{fields: {'notification': 1}});
} else {
this.ready();
}
});
客户端:
Meteor.subscribe("user-preferences", function() {
if (Meteor.user()) {
var notification = Meteor.user().notification;
// Check to see if notification and systems exists; if not, default to TRUE
if (notification) {
Session.set('aNotificationPreference', notification.hasOwnProperty('a') ? notification.a : true);
}
else {
Session.set('aNotificationPreference', true);
}
}
else {
// TRUE too if no user yet
Session.set('aNotificationPreference', true);
}
});
这是查找会话变量以使事情反应的助手:
Template.preferences.helpers({
isChecked: function() {
console.log('#### PREF INITIAL: ' + Session.get("aNotificationPreference"));
var pref = Session.get("aNotificationPreference");
if (typeof pref === 'undefined') {
Meteor.setTimeout(function() {
pref = Session.get("aNotificationPreference");
console.log('#### PREF IN TIMEOUT: ' + pref);
return pref ? 'checked' : false;
}, 1250);
}
else {
console.log('#### PREF in ELSE: ' + pref);
return pref ? 'checked' : false;
}
}
});
最后,这是 HTML 复选框字段:
<input type="checkbox" data-role="flipswitch" data-theme="b" name="aNotificationSwitch" id="aNotificationSwitch" data-mini="true" checked={{isChecked}}>
这是基于 Blaze documentation 在此专门和我发现的其他帖子上的。
我知道问题出在帮助程序中,但我不确定如何解决。失败日志如下:
Application Cache Checking event (index):1
Application Cache NoUpdate event (index):1
#### PREF INITIAL: undefined index.js?8b2a648142fb63b940f4fb04771d18f25b5bf173:63
Connected to Meteor Server. index.js?8b2a648142fb63b940f4fb04771d18f25b5bf173:37
#### PREF INITIAL: true index.js?8b2a648142fb63b940f4fb04771d18f25b5bf173:63
#### PREF in ELSE: true index.js?8b2a648142fb63b940f4fb04771d18f25b5bf173:73
Connected to Meteor Server. index.js?8b2a648142fb63b940f4fb04771d18f25b5bf173:37
#### PREF IN TIMEOUT: true
【问题讨论】:
-
似乎有很多地方出了问题。您是否一路添加了一些
console.log语句,例如,在subscribe的onReady函数中?你检查过控制台中会话变量的值吗? -
是的,就获取值而言,一切正常,但我看到的是当我看到这个失败时,助手中的 Session 变量是未定义的,所以我猜这和订阅存在竞争条件.在设置模板之前,如何强制助手等到设置该值?此外,为什么在设置会话变量后它不是响应式的,因为一旦订阅返回它就会被设置。
标签: meteor