0

I've been building a small "plugin" to reuse some code in a rails app to build and tear down select elements depending on the value of a parent select element and ajax response. All webservices and functionality worked fine until I started separating this code into something reusable. Here's the current code in coffescript:

$.fn.cascade = (urlGetter, paramGetter, callbacks)->
  callbacks[type] = callbacks[type] || $.noop for type in ["success", "notFound"]
  url = urlGetter.call(this)
  eventParams = {url: url, paramGetter: paramGetter, callbacks: callbacks}
  this.on 'change', eventParams, displayDependent

getRequest = (url, data) ->
  $.ajax (
    method: 'GET'
    url: url
    dataType: 'json'
    data: data
  )

displayDependent = (event) ->
  url = event.data.url
  params = event.data.paramGetter()
  callbacks = event.data.callbacks
  getRequest(url, params)
    .done (data, textStatus, jqXHR) ->
      statusCode = jqXHR.status
      switch statusCode
        when 200
          callbacks["success"].call(this, data)
        when 204
          callbacks["notFound"].call(this, data) 
        else console.log 'Unexpected status code: ' + statusCode
    .fail (jqXHR, textStatus, errorThrown) ->
      console.log errorThrown

This gets called on a selector this way:

$("someElement").cascade(urlGetter, paramGetter, callbacks)

So, this works the first change-event. It builds selects with expected data. The second time the change-event fires, the success Callback is receiving the same Data when the first change-event is fired, thus building the select with the old data.

How can I fix this so that data var in the .done callback changes every ajax request? I'm pretty sure I messed up something with the scope of these variables.

ballade4op52
  • 2,142
  • 5
  • 27
  • 42
mlabarca
  • 796
  • 7
  • 16

1 Answers1

0

Solution: It's the url, stupid. The Ajax method was repeating the very same request with every change event. After reading up a bit on closures and suspecting a related issue it's more plain to see url sent with change event is keeping the same value when it was defined inside. I just had to handle sending UrlGetter instead of url to displayDependent and now it works as expected.

Community
  • 1
  • 1
mlabarca
  • 796
  • 7
  • 16