2016-05-04 29 views
0

我正在嘗試在我的模板中找到Ajax調用成功的圖像...但我不能!在Ajax調用後找不到我模板中的元素

這裏是我的代碼:

class AvatarView extends Backbone.View 
    template: JST["backbone/templates/twitter_avatar"] 

    initialize:(options) -> 
    @user = options.user 

    render: => 
    @$el.html(@template({ 
     view_id: @cid 
     avatar_url: @user.avatar() || "src/image_not_found.png" 
    })) 
    @$el.find(".avatar").on('error', @_reloadAvatar) 

    _reloadAvatar: => 
    $.ajax 
     type: 'GET' 
     url: "/profiles/api/twitter/#{@user.social_network_id()}/avatar_url" 
     success: (response) => 
     if response.success 
      avatar_url = response.avatar_url 
     else 
      avatar_url = 'https://abs.twimg.com/sticky/default_profile_images/default_profile_0_normal.png' 
     @$el.find(".avatar").attr('src', avatar_url) # Here is the problem 

當調試這樣的:

  • 「本」 是AvatarView的一個實例,
  • @ $ EL是一個空div,並能」找到頭像類。

這裏是模板:

<img src="<%= avatar_url %>" alt="avatar" class="avatar" id="avatar-image-<%= view_id %>"> 

我摔倒了,我失去我的DOM對象或類似的東西..

+0

我不知道爲什麼會這樣,但是當你做'onerror'回調真正改變用戶的化身,並會發生什麼CAL:我使用的事件參數解決我的問題l再次渲染函數? – itdoesntwork

回答

0

我仍然不明白爲什麼它不工作,但

_reloadAvatar:(event) => 
$.ajax 
    type: 'GET' 
    url: "/profiles/api/twitter/#{@user.social_network_id()}/avatar_url" 
    success: (response) => 
    if response.success 
     avatar_url = response.avatar_url 
    else 
     avatar_url = 'https://abs.twimg.com/sticky/default_profile_images/default_profile_0_normal.png' 
    @(event.target).attr('src', avatar_url) 
相關問題