What's the best way to attach behavior to a Meteor Collection?

后端 未结 6 1781
陌清茗
陌清茗 2020-12-25 14:38

In Meteor, when you retrieve a record from a database, it\'s only a record. So if I have a collection called Dogs, a dog might have fur: \'br

6条回答
  •  旧时难觅i
    2020-12-25 15:10

    You can use the transform parameter in the Collection to overload the object with custom functions

    var Dogs = new Meteor.Collection("dogs", 
    {
        transform:function(entry)
        {
            entry.bark = function(){ console.log(this.barkSound);};
            return entry;
        }
    });
    

    Then:

    var aDogID = new Dogs.insert({barkSound: "ruff"})
    Dogs.find(aDogID).bark(); // "ruff"
    

    Bonus: If for any reason you would like to use a similar concept as proposed by Andrew Ferk, just use the _.defaults(object, *defaults) function.

    var defaults = {
                 barkSound: "ruff",
                 bark: function() {
                            console.log(this.barkSound);
                        }
                }
    
    Dogs = new Meteor.Collection("dogs",
            {
                transform: function(object) {
                    return _.defaults(object, defaults);
                }
            });
    

提交回复
热议问题