-1

How can I dynamically call a method from another in AlpineJS? In the example below, foo() should call bar() to run the method it receives. This doesn't work, because 'Uncaught TypeError: callback is not a function'.

foo(){
  bar(this.baz())
},
bar(method){
  method()
},
baz(){
  return 'success'
}

kslstn
  • 1,407
  • 1
  • 14
  • 34

1 Answers1

0

The issue is that you're not passing the method, you're passing the output for the method call, try

foo(){
  bar(this.baz)
},
bar(method){
  method()
},
baz(){
  return 'success'
}

If you get issues with this in baz you might need to do:

foo(){
  bar(this.baz.bind(this))
},
Hugo
  • 3,500
  • 1
  • 14
  • 28
  • Thanks. The reason I didn't even try leaving the parentheses, was that I had to pass on an argument for the method. I now solved it like this: foo(){ this.bar({method: this.baz, argument: 'success'}) }, bar(args){ m = args.method arg = args.argument m(arg) } – kslstn Jan 13 '21 at 17:30