简体   繁体   English

定义JSONP回调和CoffeeScript

[英]Scoping JSONP Callbacks and CoffeeScript

Here is my CoffeeScript: 这是我的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 这也是要点: https : //gist.github.com/1630460

The only way I could get it work, was to move the callback outside of the coffeescript 'wrap'. 我能使它工作的唯一方法是将回调移到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. 在标准coffeescript范围中, this关键字引用全局窗口对象。 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: 这是因为使用this作为参数调用闭包:

(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. 您需要做的是重命名功能window.subscribe_callback = (data)-> etc。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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