var Model = function(client, collection) {
this.client = client;
this.collection = collection;
};
Model.prototype = {
constructor: Model,
getClient: function(callback) {
this.client.open(callback);
},
getCollection: function(callback) {
var self = this;
this.getClient(function(error, client) {
client.collection(self.collection, callback);
});
},
extend: function(key, fn) {
var self = this;
this[key] = function() {
fn.call(self); // A
};
}
};
What I want to achieve is that I can “extend” the functionality of the model.
var userModel = new Model(client, 'users');
userModel.extend('create', function(data, callback) {
this.getCollection(function(error, collection) {
collection.insert(data, { safe: true }, function(error, doc) {
callback.call(doc);
});
});
});
userModel.create({ fullName: 'Thomas Anderson' }, function() {
console.log(this); // { _id: '123456789012345678901234', fullName: 'Thomas Anderson' }
});
Someway at A, I have to do parameter passing, the parameter count of the custom “create” function (data and callback) are variable.
Is this possible and if so how?
Yep! You want to use the
.applymethod over the.callmethod. Both apply context, but the.applymethod takes an array for arguments–or an arguments collection itself!