javascript - Associate a string with a function name -


i have text input want enable users call functions from.

essentially want tie strings functions when user types 'command' prefaced backslash corresponding function called.

right example's sake can type /name, followed value , set name property of user object value user gives.

so how 20 or 'commands'?

http://jsfiddle.net/k7sht/5/

jquery:

$('#textcommand').on('keypress', function(e) {         if(e.keycode==13) {             sendconsole();         } });  var user = {};  var sendconsole = function() {     value = $('#textcommand').val();     if (value.substring(0,5) === "/name") {         user.name = value.substring(6,20);         alert(user.name);     } else {         $('body').append("<span>unknown command: "+value+"</span><br />")         $('#textcommand').val("");     } } 

html:

<input id="textcommand" type="text"><br/> 

store functions in object, can retrieve , call them key:

// store functions here var commands = {     name : function() {         console.log("hello");     } }  var sendconsole = function() {     value = $('#textcommand').val();      // strip initial slash     if(value.substring(0,1) === '/') {         value = value.substring(1);          // if function exists, invoke         if(value in commands) {             commands[value](value);         }     } } 

http://jsfiddle.net/njjnb/


Comments

Popular posts from this blog

plot - Remove Objects from Legend When You Have Also Used Fit, Matlab -

java - Why does my date parsing return a weird date? -

Need help in packaging app using TideSDK on Windows -