2

How do I attach a new method to a collection object in meteorjs?

user = Meteor.user()
user.newMethod() // how/where do I attach this function?
Derek
  • 11,980
  • 26
  • 103
  • 162
  • Some related questions: http://stackoverflow.com/questions/15007231/whats-the-best-way-to-attach-behavior-to-a-meteor-collection and http://stackoverflow.com/questions/15270517/is-there-a-nice-way-to-wrap-each-meteor-user-in-an-object-with-prototype-functio – joeytwiddle Aug 16 '14 at 08:13

2 Answers2

3

The thing is Meteor.user() returns the result of something like Meteor.findOne({_id: Meteor.userId()}); so you have to redefine the entire method because there's no prototype object.

Client js, Server js or both:

Meteor.startup(function() {
    Meteor.user = function() {
       var user = Meteor.users.findOne({_id: Meteor.userId()});

       if(!user) return null;

       _.extend(user, {   // Lodash method https://lodash.com/docs/4.17.4#assign
           newMethod: function() {
              //Do something
           },
           newMethod1: function() {
              //Do something
           }
       });

       return user;
   }
});
sleep
  • 4,855
  • 5
  • 34
  • 51
Tarang
  • 75,157
  • 39
  • 215
  • 276
0

You can simply do this:

user = Meteor.user();
user.newMethod = function () {
  // Do something
};

and later on

user.newMethod();
WispyCloud
  • 4,140
  • 1
  • 28
  • 31