Search code examples
javascriptnode.jsmethod-invocation

Dynamic method creation with javascript/nodejs


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.


Solution

  • 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;