user823527
user823527

Reputation: 3712

Calling function defined in an object

I have an object that defines the name and parameters of a function to be called in the click event of a page element.

object_array = [
    {
       id: "id1",
       onclick: "load_file(filename.php);",
    },

    {
       id: "id2",
       onclick: "open_url('http://url.com');",
    }
];

That information must be retrieved dynamically. I'd like in the click event to call the onclick function for a given object in the array.

$('element').click(function() {
      // call object.onclick
});

Seems that eval() is not a good choice. Is there a different way of calling that function?

Upvotes: 1

Views: 775

Answers (3)

AlanFoster
AlanFoster

Reputation: 8306

Here's a working jsfiddle: http://jsfiddle.net/Zh6Fv/1/

Like so:

 object_array = [
        {
           id: "id1",
           // Encapsulate in an anonymous function
           onclick: function(){ load_file('filename.php'); },
        },
        {
           id: "id2",
           // Encapsulate in an anonymous function
           onclick: function(){ open_url('http://url.com'); },
        }
    ];

Then actually bind it it like this ::

$('element').click(obj.onclick);

Presumably you would be using it like this::

object_array.forEach(function(obj){
     // Note there is no need to wrap the obj.onclick
     // into another anonymous function anymore!
     $("#" + obj.id).click(obj.onclick);
});

Here's a working jsfiddle: http://jsfiddle.net/Zh6Fv/1/

Upvotes: 2

Bergi
Bergi

Reputation: 665456

You should refactor the object_array to:

[{
    id: "id1",
    action: "load_file",
    url: "filename.php"
}, {
   id: "id2",
   action: "open_url",
   url: 'http://url.com'
}];

Then you can call it with:

var actions = {
    load_file: function(url) {
        ...
    },
    open_url: function(url) {
        ...
    },
    ...
};
object_array.forEach(function(ob) {
    $("#"+ob.id).click(function() {
        actions[ob.action](ob.url);
    });
});

If you have more complex arguments, you could also deliver an arguments array instead of url and use apply() on the function.


Or, if you just want a lookup-table of functions, use:

var object = {
    "id1": function() {
        load_file('filename.php');
    },
    "id2": function() {
        open_url('http://url.com');
    }
};
$('element').click(function() {
    object[this.id]();
});

Upvotes: 2

shenhengbin
shenhengbin

Reputation: 4294

you can declare a function like

onclick : function()
{
   action(arguments);
}

Upvotes: 0

Related Questions