在 ajax 回调中设置 'this' 值

Set the 'this' value in ajax callback

我构建了一个 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))

您应该将 this 分配给一个不同的变量以备后用:

$('#rubric').on 'click', '.rubric-item .rubric-value', (e) ->
  var that = this;
  $.textToInputUpdate(
    id_for_put: $(this).parent().attr('id')
    post_url: $(this).parent().data("post-url")
    size: 3
    success_callback: (data) ->
      $(that).text(data.description)
  ).initialize(e, $(this))

只需使用 fat arrow:

$.textToInputUpdate(
  id_for_put: $(this).parent().attr('id')
  post_url: $(this).parent().data("post-url")
  size: 3
  success_callback: (data) =>
#                          ^^
    $(this).text(data.description)
)

selfthat 变量更地道的 coffeescript。