我构建了一个jquery函数,它接受选项并发出ajax PUT请求。但是我无法自定义成功回调,因为它被重新定义。有谁知道如何保持'这个'的价值?在ajax回调中设置“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
的选项
$('#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))
'自我'似乎工作,不是吗? – Bergi 2015-04-02 18:37:15
@Bergi当然,但如果你能得到正确的绑定,那么在一系列回调变得臃肿的情况下,它可以更容易地将函数分离到平等标签层次上的命名。所以,即使你很懒,并且使用'self'也很好。 – Katana314 2015-04-02 18:45:44