有没有一种很好的方法将每个Meteor.user包装在一个具有原型函数的对象中?

Mag*_*nus 5 meteor

我试图想出一个很好的方法来包装我从Meteor Accounts Collection中获取的每个用户的函数,包括一些原型辅助函数和来自其他集合的计数等.描述这个的最好方法是在代码中.

我想要包装每个用户的用户函数看起来像这样:

// - - - - - -
// 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);
    }

};
Run Code Online (Sandbox Code Playgroud)

我可以很容易地拥有一个全局'currentUser'变量,它在客户端保存有关当前登录用户的信息,如下所示:

Meteor.autorun(function() {
    if (Meteor.user()) {
        currentUser = new User(Meteor.user().profile.facebook.id);
    }
});
Run Code Online (Sandbox Code Playgroud)

将它实现到Handlebars助手中也很容易,取而代之的是{{currentUser}}这样的用法:

Handlebars.registerHelper('thisUser', function() {
    if (Meteor.user()) {
        return new User(Meteor.user());
    } else {
        return false;
    }
});
Run Code Online (Sandbox Code Playgroud)

除了这个之外我想要做的就是让Meteor返回Meteor.user()或Meteor.users.find({}).fetch()时,它包含first_name,last_name的这些辅助函数和短句柄.等

我可以以某种方式扩展Meteor.user()或有一些方法来做到这一点?

geo*_*yer 2

在 Meteor 0.5.8 中,您可以添加一个变换函数,如下所示:

Meteor.users._transform = function(user) { 
  // attach methods, instantiate a user class, etc.
  // return the object
  // e.g.: 
  return new User(user);
} 
Run Code Online (Sandbox Code Playgroud)

您可以对非用户集合执行相同的操作,但在实例化集合时也可以这样做:

Activities = new Meteor.Collection("Activities", {
  transform: function (activity) { return new Activity(activity); }
});
Run Code Online (Sandbox Code Playgroud)

(这种方式似乎不适用于“特殊”用户集合)