【问题标题】:Set the 'this' value in ajax callback在 ajax 回调中设置 'this' 值
【发布时间】: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


【解决方案1】:

只需使用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。

【讨论】:

  • 我不知道咖啡脚本中提供了胖箭头。这是要走的路。
【解决方案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))

【讨论】:

  • 为什么this 会改变?我有一个类似的问题,我在完整的回调中使用this,在回调中它从节点变为对象。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-12
  • 1970-01-01
  • 2016-09-21
  • 2017-06-17
  • 1970-01-01
  • 2017-10-01
相关资源
最近更新 更多