【发布时间】:2015-09-03 08:42:52
【问题描述】:
我正在尝试想出一个很好的方法来将我从 Meteor Accounts 集合中获取的每个用户包装在一个函数中,包括一些原型帮助函数和来自其他集合的计数等。描述这一点的最佳方式是在代码中。
我想包装每个用户的 User 函数如下所示:
// - - - - - -
// USER OBJECT
// - - - - - -
var currentUser = null; // holds the currentUser object when aplicable
function User(fbId) {
var self = this,
u = (typeof id_or_obj == 'string' || id_or_obj instanceof String ? Meteor.users.findOne({'profile.facebook.id': id_or_obj}) : id_or_obj);
self.fb_id = parseInt(u.profile.facebook.id, 10),
// Basic info
self.first_name = u.profile.facebook.first_name,
self.last_name = u.profile.facebook.last_name,
self.name = u.name,
self.birthday = u.birthday,
self.email = u.profile.facebook.email,
// Quotes
self.likeCount = Likes.find({fb_id: self.fb_id}).count() || 0;
}
// - - - - - - -
// USER FUNCTIONS
// - - - - - - -
User.prototype = {
// Get users avatar
getAvatar: function() {
return '//graph.facebook.com/' + this.fb_id + '/picture';
},
getName: function(first_only) {
return (first_only ? this.first_name : this.name);
}
};
我可以轻松地拥有一个全局“currentUser”变量,它保存有关客户端当前登录用户的信息,如下所示:
Meteor.autorun(function() {
if (Meteor.user()) {
currentUser = new User(Meteor.user().profile.facebook.id);
}
});
将它实现到 Handlebars 助手中也很容易,像这样替换 {{currentUser}} 的使用:
Handlebars.registerHelper('thisUser', function() {
if (Meteor.user()) {
return new User(Meteor.user());
} else {
return false;
}
});
除此之外我还想做的是,当 Meteor 返回 Meteor.user() 或 Meteor.users.find({}).fetch() 时,它包含这些帮助函数和短句柄名字、姓氏等
我可以以某种方式扩展 Meteor.user() 还是有什么方法可以做到这一点?
【问题讨论】:
标签: meteor