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.

0

1 Answer 1

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]();
});
Sign up to request clarification or add additional context in comments.

1 Comment

Yep that's exactly what I was looking for thank you! I'll accept the answer as soon as I"m allowed (10 minutes)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.