我遇到一个问题,当我在 Meteor 中记录 JavaScript 对象(订阅处理程序)时,我能够看到字段 0
,但无法从代码中检索它。
我正在使用 numtel:mysql
包。
以下是用于重现该问题的完整 Meteor 代码:
引导
Meteor.startup(function() {
Meteor.readLiveDb = new LiveMysql(Meteor.Config.mysql.read);
Meteor.writeLiveDb = new LiveMysql(Meteor.Config.mysql.write);
var closeAndExit = function() {
Meteor.readLiveDb.end();
Meteor.writeLiveDb.end();
process.exit();
};
// Close connections on hot code push
process.on('SIGTERM', closeAndExit);
// Close connections on exit (ctrl + c)
process.on('SIGINT', closeAndExit);
});
发布代码
Meteor.publish("checkLoginSubscription", function(username, password) {
if(typeof username === undefined || typeof password === undefined) {
throw new error('Username or password cannot be blank');
return;
}
var user = Meteor.readLiveDb.select(
'select * from users where username = "' + username + '" and password = "' + password + '"', [{
table: 'users'
}]
);
return user;
});
事件代码
Template.login.events({
'submit #loginform': function(event) {
event.preventDefault();
$('#message').fadeIn();
var username = event.target.username.value;
var password = CryptoJS.MD5(event.target.password.value).toString();
console.log('The Password entered is ', password);
if(username == '' || password == '') {
$('#message').addClass('alert-danger').removeClass('alert-success');
$('#message').html('Username or password cannot be blank');
return;
}
$('#message')
.html('<img src="img/loaders/1.gif" alt="loading" /> Logging you in...')
.addClass('alert-success')
.removeClass('alert-danger');
var cLogin = new MysqlSubscription('checkLoginSubscription', username, password);
console.log(cLogin); // This is the variable holding the object
console.log(cLogin[0]); //undefined!
}
});
在最后一行你可以看到日志:
console.log(cLogin);
当我尝试获取处理程序的 0: Object
部分时,它返回 undefined
。
出了什么问题?我如何访问这些数据?
最佳答案
Meteor 订阅是 react 性的东西。
当您转换一个时,它开始到达服务器的发布处理程序。
此发布有两种解决方法:
- 发布处理程序
返回
一个光标 - 发布处理程序调用其
ready
function (this.ready()
)
这向客户发出信号,表明出版物已准备就绪并且他可以开始使用数据。
要跟踪这一点,您需要再次 two ways :
- 原生方式:提供回调。但我不确定 SQL 订阅是否允许。
Meteor 方式(我知道您的屏幕截图支持这种方式):
ready()
。
ready()
是一个响应式(Reactive)数据源(因此是双关语)。这意味着您可以运行Tracker
computation有了它!
此类计算在 template helpers 中 native 实现.
这是使用 native Tracker 优点来实现它的另一种方法:Tracker.autorun(function doStuffOnceDataIsReady() { if(cLogin.ready()) { doStuff(); } });
看到您的用例,您可能想深入研究 template subscriptions或template computations .
关于javascript - 获取订阅处理程序的 '0' 字段返回未定义,但显示在控制台中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31865122/