I'm using Node.js and am creating some models for my different objects. This is a simplified version of what they look like at the moment.
var Foo = module.exports = function () {
var values = { type: 'foo', prop1: '', prop2: '' };
function model() {}
model.init = function(val) {
_.extend(values, val);
return model;
}
model.store = function(cb) {
db.insert(values.type, values, cb);
}
model.prop1 = function(val) {
if(!arguments.length) return values.prop1;
values.prop1 = val;
return model;
}
return model;
}
Then I can do:
var foo = Foo();
foo.init({prop1: 'a', prop2: 'b'}).store(function(err) { ... });
I then create another model:
var Bar = module.exports = function () {
var values = { type: 'foo', prop3: '', prop4: '' };
function model() {}
model.init = function(val) {
_.extend(values, val);
return model;
}
model.store = function(cb) {
db.insert(values.type, values, cb);
}
model.prop3 = function(val) {
if(!arguments.length) return values.prop3;
values.prop3 = val;
return model;
}
return model;
}
At which point I realize that a lot of the functions, like model.init
and model.store
will be reused in each of the models. But while they are exactly the same code, they depend on the local values contained in the model closure.
What's the best way to pull these functions out into a common base class that I can then use to extend all of my models with?
db
variable? Is that mongodb? – Larry Battle Sep 24 '12 at 17:27