简体   繁体   中英

Associate a string with a function name

I have a text input that I want to enable users to call functions from.

Essentially I want to tie strings to functions so that when a user types a certain 'command' prefaced with a backslash the corresponding function is called.

Right now for example's sake you can type /name , followed by a value and it will set name as a property of the user object with the value the user gives.

So how would I do this with 20 or so '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 your functions in an object, so you can retrieve and call them by key:

// Store all 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 the function exists, invoke it
        if(value in commands) {
            commands[value](value);
        }
    }
}

http://jsfiddle.net/NJjNB/

Try something like this:

var userFunctions = {
    run: function(input)
    {
        var parts = input.split(/\s+/);
        var func = parts[0].substr(1);
        var args = parts.slice(1);

        this[func].call(this, args);
    },

    test: function(args)
    {
        alert(args.join(" "));
    }
};


userFunctions.run("/test hello there"); // Alerts "hello there".

You can do:

if(window["functionName"])
{
   window["functionName"](params);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM