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

时间:2013-03-07 11:53:34

标签: 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);
    }

};

我可以很容易地拥有一个全局'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()时,它包括这些辅助函数和短句柄first_name,last_name等

我可以以某种方式扩展Meteor.user(),还是有某种方法可以做到这一点?

2 个答案:

答案 0 :(得分: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);
} 

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

Activities = new Meteor.Collection("Activities", {
  transform: function (activity) { return new Activity(activity); }
});

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

答案 1 :(得分:0)

您可以使用meteor包universe collection

这样做:

UniUsers.UniUser.prototype = {
    getAvatar: function() {
        return '//graph.facebook.com/' + this.fb_id + '/picture';
    }
};

var user = UniUsers.findOne();
console.log(user.getAvatar());

UniUsers是Meteor.users的扩展集合