e.preventDefault() email = $("#email-6ren">
gpt4 book ai didi

jquery - 界定 JSONP 回调和 CoffeeScript 的范围

转载 作者:行者123 更新时间:2023-12-01 07:26:54 25 4
gpt4 key购买 nike

这是我的 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}")

这里还有一个要点:https://gist.github.com/1630460

我可以让它工作的唯一方法是将回调移到 CoffeeScript “wrap”之外。

我的猜测是由于换行而无法访问回调。有没有聪明的方法来解决这个问题?

最佳答案

在标准coffeescript范围内,this关键字指的是全局窗口对象。因此,如果您将函数编写为

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

那么它应该和把它放在闭包外面是一样的。这是因为闭包是用 this 作为参数调用的:

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

关于jquery - 界定 JSONP 回调和 CoffeeScript 的范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8904449/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com