0

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.

3
  • Can you be more explicit about what you're trying to do in English? Please don't show code that doesn't work and then expect us to figure out what it should be doing. Commented Oct 25, 2013 at 17:16
  • var result = {}; [].forEach.call(arguments, function(arg){ result.arg = new Finder()}); return result is that what you find? Commented Oct 25, 2013 at 17:21
  • What is it you are having problem understanding? I think I explained what the module's api/usage should look like. I'm just having problems how to implement it. Commented Oct 25, 2013 at 17:22

2 Answers 2

2

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;
Sign up to request clarification or add additional context in comments.

1 Comment

I was in the middle of writing an answer with this exact same implementation then this popped up. +1 for this way of doing it
0

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.