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) { ... });
A lot of the functions, like model.init
and model.store
are going to be identical for every model, but they depend on local variables in the closure like values
.
Is there a way to pull these functions into a base class that I can then extend each of models with instead of duplicating all of this code? I would like to end up with something like this, but I'm not sure what the base
class should look like or the right way to use it to extend Foo
.
var Foo = module.exports = function () {
var values = { type: 'foo', prop1: '', prop2: '' };
function model() { this.extend(base); }
model.prop1 = function(val) {
if(!arguments.length) return values.prop1;
values.prop1 = val;
return model;
}
return model;
}
Yes you could do something like this;
model.js
/** require your db and underscore varialbles etc.. **/
module.exports = function(values, base) {
var model = typeof base == 'function' ? base : function() {};
model.init = function(val) {
_.extend(values, val);
return model;
}
model.store = function(cb) {
db.insert(values.type, values, cb);
}
return model;
}
then the usage would be similar to;
var Foo = module.exports = function () {
var values = { type: 'foo', prop1: '', prop2: '' };
var model = require('/path/to/model.js')(values);
model.prop1 = function(val) {
if(!arguments.length) return values.prop1;
values.prop1 = val;
return model;
}
return model;
}
If you need to extend the constructor
var Foo = module.exports = function () {
var values = { type: 'foo', prop1: '', prop2: '' },
model = function() { ...something here... };
require('/path/to/model.js')(values, model);
model.prop1 = function(val) {
if(!arguments.length) return values.prop1;
values.prop1 = val;
return model;
}
return model;
}