0

Many thanks for reading ,

Problem context: Use search function of spry in more than one accordion panel.

I am trying to use eval (since it is the only way I can think of) to accomplish this simple thing:

var ds1 = new Spry.Data.XMLDataSet("ajaxxmllogdaneiz1.php",'root/row]');

var ds2 = new Spry.Data.XMLDataSet("ajaxxmllogdaneiz2.php",'root/row]');

var str1="ds";

var str2= 1;

var result= str1.concat(str2);

//result is now ds1

eval ("result.filter(filterFunc)");

I would like ds1.filter(filterFunc) to be called but result.filter(filterFunc) is called. Is there a way for ds1.filter(filterFunc) to be called with eval or alternatives (Jquery?)? Many thanks Dinos

Waleed Khan
  • 11,426
  • 6
  • 39
  • 70

4 Answers4

4

You should be using this:

eval(result + ".filter(filterFunc)");

But you should really consider not evaling at all. I don't see why this would ever be advisable. If you must, I would suggest storing the variable to be operated on in a known place. For example:

​var Foo = function() {
    return {
        "bar": function() {
            console.log("baz");
        }
    }
};

var foo_list = {};
foo_list["foo"] = Foo();

var part_1 = "fo";
var part_2 = "o";

foo_list[part_1 + part_2].bar();

fiddle

(You can also store it in window this way, but I would advise against that, too.)

Waleed Khan
  • 11,426
  • 6
  • 39
  • 70
3

If the variable you're trying to access are in the global scope, then you can use:

var result = 'ds1';

window[result].filter(filterFunc);
Supericy
  • 5,866
  • 1
  • 21
  • 25
1

For using the value of result instead of "result" itself, you can do:

eval (result+".filter(filterFunc)");

techfoobar
  • 65,616
  • 14
  • 114
  • 135
  • Many thanks . I have tried combinations but I though eval () would not allow string concatanation inside. Many thanks again. – Konstantinos Chertouras Dec 30 '12 at 08:50
  • My pleasure. Note that you can pass **anything** that resolves into a string to `eval()` - be it a concatenation, a `toString()` call, a function call that returns a string, one of the string methods that return a string etc. – techfoobar Dec 30 '12 at 09:46
0

You don't need to use eval for anything less than executing completely arbitrary code.

You may want to store the XMLDataSets in an array.

var datasets = [];
for (var n=1; n<=2; n++) {
    datasets.push(new Spry.Data.XMLDataSet("ajaxxmllogdaneiz" + n + ".php", "root/row"));
}

for (var i=0; i<datasets.length; i++) {
    var ds = datasets[i];
    ds.filter(filterFunc);
}
1j01
  • 3,714
  • 2
  • 29
  • 30