Reputation: 3269
I'm trying to create a nodejs module that will have an api like this
**program.js**
var module = require('module');
var products = module('car', 'pc'); // convert string arguments to methods
// now use them
products.car.find('BMW', function(err, results){
// results
})
products.pc.find('HP', function(err, results){
// results
})
>
**module.js**
function module(methods){
// convert string arguments into methods attach to this function
// and return
}
module.find = function(query){
// return results
};
module.exports = module;
I know this is possible because this module is doing the exact same thing. I have tried to study the source but there is just to much going so was not able to determine how its doing this.
Upvotes: 0
Views: 1170
Reputation: 43718
Something like this perhaps? Kinda hard to answer without additionnal details:
function Collection(type) {
this.type = type;
}
Collection.prototype = {
constructor: Collection,
find: function (item, callback) {
//code to find
}
};
function collectionFactory() {
var collections = {},
i = 0,
len = arguments.length,
type;
for (; i < len; i++) {
collections[type = arguments[i]] = new Collection(type);
}
return collections;
}
module.exports = collectionFactory;
Upvotes: 2
Reputation: 2754
Not sure what do you want to do but remember you can have dynamic property name of an object using [] notation like ...
var MyModule = function(param1, param2) {
this.funcTemplate = function() {
console.log('Hi ');
};
this[param1] = this.funcTemplate;
this[param2] = this.funcTemplate;
};
var dynamic = new myModule('what', 'ever');
Upvotes: 0