2015-04-02 84 views
0

我構建了一個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)) 
+0

'自我'似乎工作,不是嗎? – Bergi 2015-04-02 18:37:15

+0

@Bergi當然,但如果你能得到正確的綁定,那麼在一系列回調變得臃腫的情況下,它可以更容易地將函數分離到平等標籤層次上的命名。所以,即使你很懶,並且使用'self'也很好。 – Katana314 2015-04-02 18:45:44

回答

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

更地道的CoffeeScript比selfthat變量。

+0

我不知道那個胖箭頭在coffeescript中可用。這是要走的路。 – 2015-04-02 18:41:21

2

調用jQuery函數應該分配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))