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'?
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); } } }
Comments
Post a Comment