eval function works but not the square brackets syntax

You must Login before you can answer or comment on any questions.

Hello,

I've got a function defining eventlistener for table rows based on custom properties (one for the include file, the second for the function to call in that include file):

1 - If I do this, that works:

tbl_main.addEventListener('click', createTbl_main__click_listener());
 
var createTbl_main__click_listener = function() {
    var tbl_main_click_listener = function(e) {
        if (e.rowData.link) {
            Titanium.include(e.rowData.link);
            var new_window = eval(e.rowData.window_function)();
            new_window.open();
        }
    };
return tbl_main_click_listener;
};
2 - but replacing eval with square brackets syntax returns the error "message = "'FunctionName' is not a function (evaluating 'e.rowData.window_function')";"

functionname is just the function name as a string stored in the custom property of the table view row.

tbl_main.addEventListener('click', createTbl_main__click_listener());
 
var createTbl_main__click_listener = function() {
    var tbl_main_click_listener = function(e) {
        if (e.rowData.link) {
            Titanium.include(e.rowData.link);
            var new_window =[e.rowData.window_function]();
            new_window.open();
        }
    };
 
    return tbl_main_click_listener;
};
What am i missing here ?

Thanks in advance.

1 Answer

Accepted Answer

I'm not familiar with using square bracket notation like this, but I think you could avoid using eval() altogether if you used CommonJS modules for your new windows. That would be more in line with current best practices.

It might look something like this:

// initialize a row -- you may be using a database query or a web service call,
// but this should give you the idea of how you would define one of the rows...
var row = Ti.UI.createTableViewRow ({
    title = 'class 1',
});
row.classfile = '/ui/MyWindowClass1';
 
...
 
// later in your event listener...
var WinClass = require (e.rowData.classfile);
var new_window = new WinClass ();
In your /ui/MyWindowClass1.js, you would define a window class using CommonJS and parasitic inheritance.

Out of curiosity, why do you use a factory function to create your event listener function? I've not seen that technique before, and I'm not sure there's any advantage to it.

— answered 10 months ago by Jason Priebe
answer permalink
1 Comment
  • I'm with Jason on this:

    • Eval() is and always will be dangerous. Unless you can guarantee with certainty that it will never be passed arbitrary code, it should be avoided.

    — commented 10 months ago by Stephen Feather

Your Answer

Think you can help? Login to answer this question!