Skip to content Skip to sidebar Skip to footer

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

Solution 1:

Store your functions in an object, so you can retrieve and call them by key:

// Store all functions herevar commands = {
    name : function() {
        console.log("Hello");
    }
}

var sendConsole = function() {
    value = $('#textCommand').val();

    // Strip initial slashif(value.substring(0,1) === '/') {
        value = value.substring(1);

        // If the function exists, invoke itif(value in commands) {
            commands[value](value);
        }
    }
}

http://jsfiddle.net/NJjNB/

Solution 2:

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".

Solution 3:

You can do:

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

Post a Comment for "Associate A String With A Function Name"