0

How would I create a function that accepts a value and creates a watchfile listener based on that value received?

Example of what I'm trying to do:

function createListener(id) {
  var listener(id here) = fs.watchFile(file, function () {
  });
});

How could I place the id given to function createListener(); into the listener's assigned variable?

Example: createListener('5'); would create var listener5 = fs.watchFile();

createListener('23'); would create var listener23 = fs.watchFile();

1
  • 2
    Are you sure that's what you're after? Even if you could create it, the variable would be local to the function. Would an object with the key set to the id not suffice? Then you can do watching = {}; watching[id] = fs.watchFile(); var listener = watching[id]; Commented Sep 27, 2012 at 4:39

1 Answer 1

2

You can use eval to create dynamic variable names

but it is bad part of JavaScript and I strongly recommend not to use eval at all.


I recommend you to use either array or JSON objects to store multiple functions.

Array

var functions = [];
functions.push = function () { ... };

// functions = [ function () { ... } ];

JSON

var functions = {};
functions["one"] = function () { ... };

// functions = { one: function () { ... } };
Sign up to request clarification or add additional context in comments.

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.