【发布时间】:2015-04-04 22:03:39
【问题描述】:
我构建了一个 jquery 函数,该函数接受选项并发出 ajax PUT 请求。但是我在自定义成功回调时遇到了麻烦,因为它被重新定义了。有谁知道如何保持“this”的价值?
jquery 函数
(($) ->
$.textToInputUpdate = (options) ->
functionality =
options: $.extend({
'id_for_put': ""
'post_url': ""
'size': 10
}, options)
initialize: (event, target) ->
# ...
self = this
field.focusout (event) ->
$.ajax
url: self.options.post_url
type: 'PUT'
dataType: "json"
data:
rubric_item:
weight: parseFloat(field.val().trim())
success: (data) ->
self.options.success_callback?(data)
return functionality
) jQuery
使用选项调用 jquery 函数
$('#rubric').on 'click', '.rubric-item .rubric-value', (e) ->
$.textToInputUpdate(
id_for_put: $(this).parent().attr('id')
post_url: $(this).parent().data("post-url")
size: 3
success_callback: (data) ->
# PROBLEM HERE: $(this) gets redefined when actually called in the function above. I want it to be the value of $(.rubric-value).
$(this).text(data.description)
)
.initialize(e, $(this))
【问题讨论】:
-
self似乎有效,不是吗? -
@Bergi 当然,但是如果您可以正确绑定,那么如果/当一系列回调变得臃肿时,它可以更容易地将函数分离为相同选项卡级别的命名函数。因此,即使您很懒惰并使用
self,仍然很高兴。
标签: jquery ajax coffeescript