C. Ovidiu C. Ovidiu - 3 months ago 11
Javascript Question

jQuery: use dynamic object based on variable value

I have several objects and all of them have some methods that are called the same but do different things.


When I click a button, I want to call the
init()
method, but the
object is different based on what button I clicked.


Here is a snippet

$btn.on('click', function(e){

e.preventDefault();

var $trigger = $(this);
var objectName = $trigger.data('object');

/*
if objectName is 'user', I want to call user.init(),
if it's 'product' I want to call product.init() and so on...
right now i get an error if I call like his
*/
objectName.init($trigger);

});


Is it possible to dynamically call an object like this ? I know it is for its properties and methods, but I din't find anything about this issue.

Thank you.

Answer

It's better to do mapping

var entities = {
    user: user,
    entity: entity
}

var objectName = $trigger.data('object');

entities[objectName].init($trigger);
Comments