Callable in Javascript

3

I have a list of id's in buttons:

<button id="grafico01">Pontuação por MARCAS</button>
<button id="grafico02">Pontuação por EQUIPAMENTOS</button>
<button id="grafico03">RAZÃO da Pontuação</button>

... that become functions:

function grafico01(){...
function grafico02(){...
function grafico03(){...

I deal with a function that receives the ID's of the buttons:

$("button[id^=grafico]").click(function() {...

Depending on the ID's, call the corresponding function, but I have not been successful with typeof and instanceof .

Is there any way I can call these functions through a received name, like the callable operation of PHP?

    
asked by anonymous 29.06.2016 / 15:08

2 answers

2

If these functions are in global scope you can do something like

window[this.id]();

If you do not have to create an object with these functions and then use it in the same way but using that object instead of window

Example: link

    
29.06.2016 / 15:14
2

See if this matches what you want

var graphFuncs = {
  grafico01: function() {
    alert('função grafico1');
  },
  grafico02: function() {
    alert('função grafico2');
  },
  grafico03: function() {
    alert('função grafico3');
  }
}

$('button[id^=grafico]').on('click', function() {
  var func = $(this).prop('id');
  graphFuncs[func]();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><buttonid="grafico01">Pontuação por MARCAS</button>
<button id="grafico02">Pontuação por EQUIPAMENTOS</button>
<button id="grafico03">RAZÃO da Pontuação</button>
    
29.06.2016 / 15:13