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.