Greg.Forbes
Greg.Forbes

Reputation: 2814

use text passed to a function to call a javascript function

I am trying to figure out how to call a javascript function using text taken off an div id using jquery like this:

$('#selector').attr('id');

The id returned is a text object, which I want to use to call an javascript object of the same name. Basically I have an appointment in a calendar and set of objects holding the various variables such as reason, times, locations etc in the background. These objects have been created using a custom constructor function like this.

function appt(id,...){
  this.id;
  etc...
 }
 var appt12 = new appt(id,...);

I then want to be able to call it as an object along the lines of var id = appt12.id.

I have found I can use eval to do this, but there seems to be a lot of debate in this forum on the use of eval. I am concerned it could be slow, on security it will only be called in browser so most of the security will occur in my php.

Using eval would look like this:

var apptObj = eval(apptid);

after passing to eval the text id can be used as a reference to an object. Although my reading of other posts is that this is not best practice.

Any thoughts on a non-eval approach to solving this problem.

Thanks in advance.

Upvotes: 0

Views: 84

Answers (2)

Ufuk Hacıoğulları
Ufuk Hacıoğulları

Reputation: 38468

If the function you are tyring to call is global, you can reach it by window object's index.

//get the function first
var myFunction = window[functionName];

//call the function with your parameters
myFunction(param);

Update:

If I understand correctly you are trying to create variables using ids, if that's the case you can do it this way:

window['appt'+id] = appt(id);

Like Dennis mentioned it would be better if you don't use global variables. Instead you can hold all these variables in another object. Here's an example:

//initialize it if it is undefined
var apptHolder = apptHolder || {};

//assign the property
apptHolder['appt'+id] = appt(id);

//if you need the apptHolder to be global
window.apptHolder = apptHolder;

Upvotes: 0

Dennis
Dennis

Reputation: 32598

You should hold the functions in an object like this:

var operations = {
    "add": function(){...},
    "remove": function(){...},
    "edit": function(){...}
};

Then call it like this:

var op = element.id;
operations[op]();

You could use the global window object that Ufuk mentioned, but it is generally frowned upon. If you have several related functions, keeping them in an object and preventing them from floating in the global scope is considered cleaner and more organized.

Upvotes: 1

Related Questions