1

I'm trying to declare a click handler using an array of strings which contains the selectors and corresponding methods to call:

['start','clear','stop','plus','minus'].forEach(function(el) {
    $("#" + el).click(function() { 
        Timer.el();     
    });
});

The point is to change Timer."array[index]"();. I tried el but the console shows an error.

1
  • 1
    It's a case of bracket notation vs dot notation. Commented Mar 9, 2016 at 18:39

1 Answer 1

1

To programmatically call a method of an object you need to use bracket notation. Try this:

['start','clear','stop','plus','minus'].forEach(function(el) {
    $("#" + el).click(function() { 
        Timer[el](); 
    });
});

Working example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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