I've searched around a lot, but I just can't grasp the fundamentals of returning data from an ajax call's success method. I'm normally ruby dev, and fully understanding js/coffeescript's best practices have been a hurdle.
I have a CS file that does something like this:
$ ->
$.when(Foo.load()).done (data) ->
# manipulate data
But this "data" comes from either a cached object in the browser, or an ajax call's successful response. Here's some info on the Foo class
class @Foo
_now = new Date().getTime()
_expiration = new Date(_now).setHours(24, 0, 0, 0) #24 hours from now
@save: (data) ->
record = { value: JSON.stringify data, timestamp: _expiration }
localStorage.setItem('responseData', JSON.stringify record)
@load : ->
record = JSON.parse localStorage.getItem('responseData')
if record and _now < record.timestamp
JSON.parse record.value
else
Foo.refresh()
@refresh : ->
$.ajax(
url: '/data'
dataType: 'JSON'
type: 'post'
async: false
success: (data) ->
Foo.save data.results
)
Foo.load()
The problem stems from the load and refresh methods. As you can see, we can result in an infinite loop. load calls refresh which will call load which will call refresh and so on.
What I am looking for is a way to return the response from the ajax method in the load() method, so it performs the same way as the JSON.parse record.value
if record and _now < record.timestamp
JSON.parse record.value
else
# RETURN the result of the successful ajax call, this would mean that when we call $.when(Foo.load()).done we would have waited for the ajax call to run.
If anyone has any tips, they would be much appreciated! I will gladly elaborate as needed.
Would the ajax call async attribute have anything to do with it? I was thinking it was the behavior of the 2 class methods in Foo