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.
You need to use a bracket notation
b.on("click", window[method_name](event))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With