0

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.

1
  • var objectName = JSON.parse($trigger.data('object')); Commented Aug 17, 2016 at 12:29

3 Answers 3

3

It's better to do mapping

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

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

entities[objectName].init($trigger);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, this seems the cleanest solution.
1

In case your objects (or functions) defined in the global scope, you can access them using the window object:

var funcT = function() {
  console.log('funcT was called');
}

var objT = {
  'a': 1,
  'b': 2
}
function a() {
  var funcName = 'funcT'
  window[funcName]();
  
  var objName = 'objT'
  console.log(window[objName]);
}

a()

Comments

1

With window[variable] you can access variables based on another variable.

So all that you need to do is to replace objectName.init($tr‌​igger); with: window[objectName].‌​init();

1 Comment

They are not global, so I'll stick with Maxx's response. But thank you anyway

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.