1

I'm trying to rid my code of a couple of evals that I have in my javascript, but I'm not sure of the best way to achieve what I'm trying to do.

I have a "filter form" on a bunch of my pages, with a bit of JS attached to it that reloads parts of the page depending on what the user does.

Different pages require different actions though.

So my solution (that I came up with yearrrrs ago...) was

<form name="callback_loadCalendar">
<form name="callback_loadNames">

Etc.

And this horrible bit of JS (attached to onchange events etc) to then call the relevant function:

if (f.getAttribute('name') && f.getAttribute('name').indexOf('callback') === 0)
    eval(f.getAttribute('name').substr(9)+'()');

E.g. that would call loadCalendar() and loadNames() respectively.

What SHOULD I be doing instead?

Thanks!

Codemonkey
  • 4,455
  • 5
  • 44
  • 76

1 Answers1

2

If the functions are in the global scope, then you can use bracket notation in the global scope to access the function references.

window[f.getAttribute('name').substr(9)]();
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Perfect, and so simple, thankyou! I assumed I'd have to do some major recoding on all fronts to achieve this in a completely different manner. – Codemonkey Jan 05 '16 at 12:09
  • Ah, and if they're not? Will this work if they're all wrapped in an IIFE? It should do, I suppose? – Codemonkey Jan 05 '16 at 12:09
  • @Codemonkey in that case you can do something like `var callbacks = {loadNames: function(){}, loadCalendar: function(){}}`, then `callbacks[f.getAttribute('name').substr(9)]();` – Arun P Johny Jan 05 '16 at 12:13