这是重写Meteor.Collection以支持对象方法的开始。
Meteor.Kollection = Meteor.Collection;
Meteor.Kollection.extend = function(constructor) {
var parent = this;
var child = function() {
Meteor.Kollection.apply(this, arguments);
constructor.apply(this, arguments);
};
_.extend(child, parent);
function __proto__() { this.constructor = child; };
__proto__.prototype = parent.prototype;
child.prototype = new __proto__;
return child;
};
Meteor.Collection = Meteor.Kollection.extend(function(name, options) {
if (options && options.defaults) {
this.defaults = options.defaults;
}
});
Meteor.Collection.prototype.applyDefaults = function(attrs) {
return _.defaults(attrs, this.defaults);
};
Meteor.Collection.prototype.create = function(attrs) {
if (typeof attrs !== "object") attrs = {};
return this.applyDefaults(attrs);
};
Meteor.Collection.prototype.findOne = function(selector, options) {
var object = Meteor.Kollection.prototype.findOne.apply(this, arguments);
return this.applyDefaults(object);
};
你可能会注意到新的
collection.create方法,以及
collection.findOne已被覆盖。我想所有的
collection.*方法都需要被覆盖,但这是一个开始。
那么你可以用它做什么呢?
var Dogs = new Meteor.Collection("dogs", { defaults: {
barkSound: "ruff",
bark: function() {
console.log(this.barkSound);
}
}});
if (Meteor.isClient) {
var regularDog = Dogs.create();
regularDog.bark();
var smallDog = Dogs.create({
barkSound: "yip"
});
smallDog.bark();
Dogs.insert(smallDog, function(error, id) {
Dogs.findOne(id).bark();
});
});
我不确定这是如何发生的,但当一个对象中的函数被插入时,它们会被移除。因此,我们可以直接将方法应用于对象。首先,通过传递带有
defaults
属性的对象来创建集合。该属性可以包括属性或方法。要为给定的集合创建新对象,请使用
collection.create(attrs),其中 attrs 是一个选项参数,包括附加或覆盖的属性和方法。