javascript - Dispatch on select element without eval or copy & paste -


edit: question duplicate of "how call javascript function when have string containing name". dom interaction distraction.

i call 1 of n distinct javascript functions when user chooses option html select element. i'd without repeating myself or regressing eval().

revision 1 stored strings in option's value field, used these indexes dictionary.

<body> <select onchange="dispatch(this)"> <option value="first_function_name">one</option> <option value="second_function_name">two</option> </select> </body>  <script> function first_function() {console.log("there can one");} function second_function() {console.log("except when there two");} function dispatch(selection) {   var name = selection.value;   var lookup_table = {     first_function_name: first_function,     second_function_name: second_function   };   (lookup_table[name])(); } </script> 

revision 2 stores functions in value field , calls eval on it. eval strikes me absurdly heavy handed.

<body> <select onchange="dispatch(this)"> <!-- not sure passing ok --> <option value="first_function()">one</option> <option value="second_function()">two</option> </select> </body>  <script> function first_function() {console.log("there can one");} function second_function() {console.log("except when there two");} function dispatch(selection) {eval(selection.value);} /* yuck */ </script> 

option 3 aim code generator @ problem, seems defeatist. sane, idiomatic solution this?

var closureobject = (function(){    // created scope      /* "this" becomes closureobject , has functions property ,         can directly refer them syntax instance['propertyname'] */      var closureobject = {};      closureobject.first_function = function() {            alert("there can one");      }      closureobject.second_function = function(){            alert("except when there two");      }      return closureobject;      })();    function dispatch(selection) {            closureobject[selection](); // closureobject global or scoped variable  }
<select onchange="dispatch(this.value)">  <option value="first_function">one</option>  <option value="second_function">two</option>  </select>


Comments

Popular posts from this blog

python - Healpy: From Data to Healpix map -

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -