Building the name of a function and executing it

0

I have an object that is made up of several functions. these functions are names of tables that, from an earlier treatment I have to execute them. The idea of the code is, if a table does not exist, execute such a function that will create it based on your code.

Below is the function:

//WebSQL connect db
d = openDatabase('test', 'test', 'app', 200 * 1024 * 1024);
db = {
    stage : function(){
        //app tables
        var sys_tables = ['license','config'];
        //verify integrity from database
        d.transaction(function (tx) {
            //sql
            tx.executeSql('SELECT name FROM sqlite_master',[],function(tx, result){
                //catch num rows in select
                var len = result.rows.length, i;
                //for for in sql, search if this val exist in sys_tables
                for (i = 0; i < len; i++){
                    //if not exist, call function to create this table
                    if($.inArray(result.rows.item(i).name , sys_tables) < 0){
                        var table = 'db.make'+result.rows.item(i).name+'()';
                        //>>>>>>>>>>>>HELP HERE<<<<<<<<<<<<
                        console.log(table);
                        //>>>>>>>>>>>>HELP HERE<<<<<<<<<<<<
                    }     
                };
            },null);
        });
    },

    make : {
        //create a license table...
        license : function(){
        //code...
        },
        //create a config table...
        config : function(){
        //code...
        }
    }
}

Does anyone have a solution for this? I can not think of a way for me to logically name my functions and call them. and I do not want to do a series of cases, because in this case with each new table I would have to modify this function (unnecessary reprogramming in my view) ...

Any help?

    
asked by anonymous 10.11.2014 / 18:39

1 answer

1

Accessing object attributes as associative array

JavaScript allows you to access the attribute values of an object through a similar mechanism - other than itself - to associative arrays :

var db = {
    make: {          // Objeto de interesse (db.make).
        att0: "1",
        att1: "2",
        att2: "3"
    }
};

// Acessando os atributos do objeto de interesse (db.make):
for(var i = 0; i < 3; i++) print(db.make["att" + i]);

// Função de comodidade para imprimir o resultado. Ignore-a :)
function print(source){
    var p = document.createElement("p");
    p.innerHTML = source;
    document.body.appendChild(p);
}

Accessing object-function attributes

In this way, if the attributes of the object in question are functions , to call them, just do objeto["prefixo" + indice]() , according to the following example:

var db = {
    make: {          // Objeto de interesse (db.make).
        mk0: function(){
            print("Criar tabela 1...");
        },
        mk1: function(){
            print("Criar tabela 2...");
        },
        mk2: function(){
            print("Criar tabela 3...");
        }
    }
};

// Acessando os atributos do objeto de interesse (db.make):
for(var i = 0; i < 3; i++) db.make["mk" + i]();

// Função de comodidade para imprimir o resultado. Ignore-a :)
function print(source){
    var p = document.createElement("p");
    p.innerHTML = source;
    document.body.appendChild(p);
}

Non-numeric indices

Our index i is numeric to facilitate demonstration; however, the index can assume any possible form of string , so as to concatenate properly with the function prefix.

In your case, there are a number of identifiers (names). Even if they have accents, spaces, and punctuation , once the string resulting from the concatenation between the prefix and the key (index) is able to "match" with an object attribute, the corresponding function can be called . Therefore, it suffices to have ( or not , as we will see later), for each possible key, a respective function, according to the example below:

var chaves = [
    ", mundo",
    ", SO"
];
var obj = {
    "olá, mundo": function(){
        print("Olá, mundo.");
    },
    "olá, SO": function(){
        print("Olá, Stack Overflow em Português!");
    }
};
for(var c in chaves) obj["olá" + chaves[c]]();

// Função de comodidade para imprimir o resultado. Ignore-a :)
function print(source){
    var p = document.createElement("p");
    p.innerHTML = source;
    document.body.appendChild(p);
}

What if the function does not yet exist?

The associative array engine lets you check, at runtime, whether a function already exists, before invoking it. Better than that: the language allows you to declare the function, on the run , if it does not already exist. With closures, the function can even save values from the moment of declaration into your memory :

var chaves = [
    ", mundo",
    ", SO"
];

var obj = {};

for(var c in chaves){
    // Se a função não existir, declara-a, embrulhando sua chave numa closure:
    if(! obj["olá" + chaves[c]]) obj["olá" + chaves[c]] = (function(){
        var thisChave = chaves[c];
        return function(){
            print("Olá" + thisChave + ".");
        };
    })();
    
    // Após isso, podemos chamá-la, na certeza de que existe:
    obj["olá" + chaves[c]]();
}

// Função de comodidade para imprimir o resultado. Ignore-a :)
function print(source){
    var p = document.createElement("p");
    p.innerHTML = source;
    document.body.appendChild(p);
}

Closures are powerful and can be used in many different ways; with the help of associative array technique, possibilities expand; I believe you can mechanize your task of declaring functions.

If in doubt about closures, there is a lot of stuff right here in SOpt:)

    
10.11.2014 / 20:48