0

In PHP it is possible to chain a method dynamically using a variable. For example:

$foo = 'myFunction';
return $this->{$foo};

I was wondering if a similar possibility exists in jQuery and/or Javascript. So for example:

$('body').on('keyup', '[function-attribute=myFunction]', function(){
    var foo = $(this).attr('function-attribute');

    return {foo}();
});

I understand the code above does not work but just hopefully gives an impression of what I'm trying to achieve.

James
  • 190
  • 2
  • 4
  • 13

1 Answers1

1

If the function is declared globally then you can access it via the window using bracket notation:

$('body').on('keyup', '[function-attribute=myFunction]', function(){
  var foo = $(this).attr('function-attribute');
  return window[foo]();
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Yep that's exactly what I was looking for thank you! I'll accept the answer as soon as I"m allowed (10 minutes) – James Aug 13 '19 at 13:56