ericbae
ericbae

Reputation: 9644

Backbone, Coffeescript - passing function as a callback in AJAX

In my Backbone View, I have two methods, one does a simple AJAX call, and the other is the callback function I want to run. I want to call the AJAX method with the callback function as its parameter.

call_ajax_function: =>
  @get_stuff(@my_callback)

get_stuff: (callback_function) =>
  $.ajax
    url:'get_something'
    success: =>
      callback_function

my_callback: =>
  console.log "hello"

But I don't think "my_callback" is getting called. Any ideas?

Upvotes: 2

Views: 2950

Answers (1)

hvgotcodes
hvgotcodes

Reputation: 120198

You need to invoke your function, try changing

get_stuff: (callback_function) =>
  $.ajax
    url:'get_something'
    success: =>
      callback_function

to

get_stuff: (callback_function) ->
  $.ajax
    url:'get_something'
    success: (data) => #success takes arguments, pass them thru
      callback_function(data)

I think you don't need to pass the argument into get_stuff like you are doing. So I think this should work

get_stuff: ->
  $.ajax
    url:'get_something'
    success: (data) => 
      @callback_function(data)

Plus, it should have the advantage that the context of the callback will be the instance, i.e. within the callback execution @ will be the correct instance.

If you want to specify the callback method dynamically, AND you want to specify the scope on which that method executes, you need to use call like so

get_stuff: (onSuccess)->
      $.ajax
        url:'get_something'
        success: (data) => 
          onSuccess.call @, data

As a note, when defining methods on a class, I don't thing => is buying you anything. Use -> for those methods. Use => when you want to look the context into an anonymous function.

Upvotes: 3

Related Questions