Created
August 15, 2012 05:15
-
-
Save limeyd/3356221 to your computer and use it in GitHub Desktop.
Meteor injected Models
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Model = function(attrs) { | |
attrs = attrs || {}; | |
_.extend(this, attrs); | |
_raw_attr_keys = _.keys(attrs); | |
this.errors = {}; | |
} | |
Model.bind = function(model, collectionName){ | |
var pt = new Model({}); | |
_.extend(pt, model.prototype); | |
model.prototype = pt; | |
model.prototype.constructor = model; | |
model._collection = new Meteor.Collection(collectionName); | |
model.clear = function(){ | |
model._collection.remove({}); | |
} | |
model.remove = function(selector,options){ | |
selector = selector || {}; | |
options = options || {}; | |
model._collection.remove(selector,options); | |
} | |
model.findOne = function(selector,options){ | |
selector = selector || {}; | |
options = options || {}; | |
return model._collection.findOne(selector,options); | |
} | |
model.find = function(selector,options){ | |
selector = selector || {}; | |
options = options || {}; | |
return model._collection.find(selector,options); | |
} | |
// wrap it good!!! | |
var c = model._collection._collection.constructor; | |
c.__deepcopy = c._deepcopy; | |
c._deepcopy = function(v){ | |
var dc = c.__deepcopy(v); | |
if (typeof dc !== "object"){ | |
return dc; | |
} | |
return new model(dc); | |
} | |
} | |
Model.prototype = { | |
persisted: function() { | |
return ('_id' in this && this._id != null); | |
}, | |
save: function() { | |
var data = _.pick(this,_raw_attr_keys); | |
if (this.persisted()) { | |
this.constructor._collection.update(this._id,data); | |
} else { | |
this._id = this.constructor._collection.insert(this,data); | |
} | |
return this; | |
}, | |
update_attrs: function(attrs) { | |
_.extend(this,attrs); | |
_raw_attr_keys = _.union(_raw_attr_keys, _.keys(attrs)); | |
return this.save(); | |
}, | |
track_attr: function(key) { | |
_raw_attr_keys = _.union(_raw_attr_keys, key); | |
return this.save(); | |
}, | |
destroy: function() { | |
if (this.persisted()) { | |
this.constructor._collection.remove(this._id); | |
} | |
} | |
} | |
var Request = function(attrs){ | |
Model.call(this,attrs); | |
} | |
// extend request with instance methods | |
Request.prototype = { | |
prefixed: function(){return '---'+this.name;} | |
}; | |
// make it all worth while. | |
Model.bind(Request,'requests'); | |
// usage | |
var r = new Request({title:'I want more apples'}); | |
r.save() | |
Request.find(); //collection cursor | |
Request.findOne(); //object; | |
r.update_attrs({'body','lorem....'}); | |
r.date = Date.now(); | |
r.track_attr('data'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment