简体   繁体   中英

Scoping JSONP Callbacks and CoffeeScript

Here is my CoffeeScript:

jQuery -> 
  $("form").submit (e) -> 
    e.preventDefault() 
    email = $("#email").val() 
    return if email.length == 0 
    $.ajax 
      url: "https://api.kickofflabs.com/v1/1905/subscribe", 
      data: "email=#{email}", 
      dataType: 'jsonp', 
      jsonp: 'jsonp',
      jsonpCallback: 'subscribe_callback', 
      timeout: 2000, 
      error: (a, b, e) -> 
        alert e
        console.log e

subscribe_callback = (data) ->
  console.log(data) 
  alert("Signed up #{data.email}")

Here is a gist as well: https://gist.github.com/1630460

The only way I could get it work, was to move the callback outside of the coffeescript 'wrap'.

My guess is the the callback can not be accessed because of the wrap. Is there a smart way to work around this?

In standard coffeescript scope the this keyword refers to the global window object. So if you write your function as

this.subscribe_callback = (data) ->
  console.log(data) 
  alert("Signed up #{data.email}")

Then it should be the same as putting it outside of the closure. This is because the closure is invoked with this as a parameter:

(function(this) {
   // your code
})(this)

I imagine the reason it's not working is because the context in which it'll look for your function will be the top one, ie the window.

What you'll need to do is rename the function window.subscribe_callback = (data)-> etc instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM