问题描述
我正在尝试想出一个很好的方法来将我从 Meteor 帐户集合中获取的每个用户包装在一个函数中,包括一些原型辅助函数和来自其他集合的计数等.描述这一点的最佳方法是在代码中.
I'm trying to come up with a nice way to wrap each user I fetch from the Meteor Accounts Collection in a function, including a few prototype helper functions and counts from other collections, etc. The best way to describe this is in code.
我想包装每个用户的 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}}
的使用:
It's also easy to implement this into a Handlebars helper, replacing the use of {{currentUser}}
like this:
Handlebars.registerHelper('thisUser', function() {
if (Meteor.user()) {
return new User(Meteor.user());
} else {
return false;
}
});
除此之外我还想做的是当 Meteor 返回 Meteor.user() 或 Meteor.users.find({}).fetch() 时,它包含这些辅助函数和短句柄名字、姓氏等
What I want to do in addition to this is to make it so that when Meteor returns Meteor.user() or Meteor.users.find({}).fetch(), it includes these helper functions and short handles for first_name, last_name, etc.
我能否以某种方式扩展 Meteor.user() 或者有什么方法可以做到这一点?
Can I somehow extend Meteor.user() or is there some way to do this?
推荐答案
在 Meteor 0.5.8 中,你可以像这样添加一个变换函数:
In Meteor 0.5.8, you can just tack on a transform function like so:
Meteor.users._transform = function(user) {
// attach methods, instantiate a user class, etc.
// return the object
// e.g.:
return new User(user);
}
您可以对非用户集合执行相同的操作,但在实例化集合时也可以这样做:
You can do the same with non-user collections, but you can also do it this way when you instantiate the Collection:
Activities = new Meteor.Collection("Activities", {
transform: function (activity) { return new Activity(activity); }
});
(这种方式似乎不适用于特殊"用户集合)
(this way doesn't seem to work with the 'special' users collection)
这篇关于有没有一种很好的方法可以将每个 Meteor.user 包装在一个带有原型函数等的对象中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!