在ajax回调中设置'this'值

时间:2015-04-02 18:35:22

标签: jquery ajax coffeescript

我构建了一个jquery函数,它接受选项并发出ajax PUT请求。但是我在定制成功回调时遇到了麻烦,因为这被重新定义了。有谁知道如何保持'这个'?

的价值

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))

2 个答案:

答案 0 :(得分:3)

只需使用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变量更多的惯用咖啡因。

答案 1 :(得分:2)

您应该将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))