Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Coffeescript getting proper scope from callback method

I've searched for this and can't seem to find an successful answer, I'm using a jQuery ajax call and I can't get the response out to the callback.

Here's my coffeescript code:

initialize: (@blog, @posts) ->
    _url = @blog.url
    _simpleName = _url.substr 7, _url.length
    _avatarURL = exports.tumblrURL + _simpleName + 'avatar/128'
    $.ajax
        url: _avatarURL
        dataType: "jsonp"
        jsonp: "jsonp"
        (data, status) => handleData(data)

handleData: (data) =>
    console.log data
    @avatar = data

Here's the compiled JS:

  Blog.prototype.initialize = function(blog, posts) {
    var _avatarURL, _simpleName, _url,
      _this = this;
    this.blog = blog;
    this.posts = posts;
    _url = this.blog.url;
    _simpleName = _url.substr(7, _url.length);
    _avatarURL = exports.tumblrURL + _simpleName + 'avatar/128';
    return $.ajax({
      url: _avatarURL,
      dataType: "jsonp",
      jsonp: "jsonp"
    }, function(data, status) {
      return handleData(data);
    });
  };

  Blog.prototype.handleData = function(data) {
    console.log(data);
    return this.avatar = data;
  };

I've tried a dozen variations and I can't figure out how to write this?

Thanks.

like image 672
pandabrand Avatar asked Oct 09 '22 06:10

pandabrand


2 Answers

Your arguments are incorrect, you are passing the callback as the second parameter to $.ajax. You should pass it as success: in the options, or add it to the Ajax deferred object.

Since handleData looks like it is attached to an object, which is likely this, you need to prefix it with @.

While your way of passing the URL works, the API now suggests passing the URL as the first param and the options as the second.

$.ajax _avatarURL,
  dataType: "jsonp"
  jsonp: "jsonp"
  success: (data, status) => @handleData(data)

OR

$.ajax _avatarURL,
  dataType: "jsonp"
  jsonp: "jsonp"
.done (data) => @handleData(data)
like image 72
loganfsmyth Avatar answered Oct 12 '22 19:10

loganfsmyth


Since handleData is in Blog's prototype, not a variable in scope, you probably want this:

(data, status) => @handleData(data)
like image 23
Ricardo Tomasi Avatar answered Oct 12 '22 20:10

Ricardo Tomasi