Callable in Javascript

Asked

Viewed 57 times

3

I have a list of id’s on 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 gets the button Ids:

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

Depending on the ID’s, call the corresponding function, but I haven’t been succeeding with typeof and instanceof.

Have some way I call these functions through a received name, like PHP callable running?

2 answers

2

See if this goes with 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>
<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>

  • Is it necessary for me to throw the functions into a variable? That way encapsulated it could work as much as the answer above. I will test.

  • We respond almost simultaneously with the same answer :) +1

  • Yap :) @Sergio. I’ve also put you +1

  • For my functionality, both worked, but @Sergio’s wiped my code more.

  • No problem @Williamasimiliar, they both work but you have to accept the best for you

2


If those functions are in the global scope you can do something like

window[this.id]();

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

Example: https://jsfiddle.net/bkrfyjdv/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.