Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mapping strings to functions in javascript

I'd like to make it so that based on the value of an HTML attribute in a list of HTML elements, that I can call a different javascript function based on the value of that attribute's string value.

basically what I want is a map from string => function in javascript / jQuery. (and then of course be able to call this function).

is this possible?

like image 932
lol Avatar asked Jul 25 '12 20:07

lol


1 Answers

Yes:

var fnMap = {
  "foo": function() { ... },
  "bar": function() { ... },
  // ...
};

If your functions already exist, you can just reference them by name:

var fnMap = {
  "foo": someFunction,
  "bar": otherFunction,
  // ...
};

and you can mix the two styles.

To call one of the functions based on a value:

fnMap[ value ]( param, param, ... );
like image 54
Pointy Avatar answered Sep 19 '22 11:09

Pointy