Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent in Javascript/Coffeescript/jQuery to Ruby's send?

If I have a method name in a string, in Ruby I can use send to dynamically dispatch methods, e.g.

method_name = "delete"
send method_name

I can take advantage of interpolation too:

method_name = "add"
send "#{method_name}_task", args

I've 2 functions defined in javascript, one to delete, one to update something. A button for each is dynamically added and, at the moment, just the delete method gets bound via button.on "click", e.g.

b.on "click", (event) ->
  event.preventDefault() # stop submission via postback
  this_button = $(this)
  task_id = this_button.data("task-id")
  delete_task( task_id, this_button )
  false

I'd like to be able to do this:

method_name = "delete"
b.on "click", (event) ->
  event.preventDefault() # stop submission via postback
  this_button = $(this)
  task_id = this_button.data("task-id")
  send "#{method_name}_task", task_id, this_button
  false

The only difference between the binding of the 2 functions is this one line. If there's an obvious way, it'd be helpful to cut down on the repetition. I haven't found anything in my searches, so if anyone could help it would be much appreciated.

like image 693
ian Avatar asked Jul 23 '13 08:07

ian


1 Answers

You need to use a bracket notation

 b.on("click", window[method_name](event))
like image 176
Konstantin Rudy Avatar answered Oct 05 '22 02:10

Konstantin Rudy