ai / evil-blocks

Tiny framework for web pages to split your app to separated blocks
MIT License
128 stars 10 forks source link

Accessing @var from ajax callback #34

Closed nleo closed 9 years ago

nleo commented 9 years ago

First of all I'm a backend developer with a little fronend background and I start using this gem with hope it's helps me to handle frontend scenarios easier.

I wrote a code:

evil.block '@@photo',

  init: ->
    console.log 'init on @@photo'
    console.log @photo_div
    @prev_div.css( 'cursor', 'url(http://i.imgur.com/r2FFM1i.png), auto' )
    @next_div.css( 'cursor', 'url(http://i.imgur.com/kGYEBSo.png), auto' )

  updateImage: (url) ->
    $.getJSON url, (json)->
      url = json.photo.photo.url
      window.nextPhotoId = json.next_id
      window.prevPhotoId = json.prev_id
      @photo_div.html(json.photo_rendered)

  'click on @prev_div': (e)->
    @updateImage '/photos/'+window.prevPhotoId+'.json'

  'click on @next_div': (e)->
    @updateImage '/photos/'+window.nextPhotoId+'.json'

I can access @photo_div in init, but not in getJSON callback

TypeError: this.photo_div is undefined
return this.photo_div.html(json.photo_rendered);

At beginning I thinking about using events, but review examples and found that adding photo_div = @photo_div make it work

  updateImage: (url) ->
    photo_div = @photo_div
    $.ajax
      url: url
      success: (json, status, xhr)->
        url = json.photo.photo.url
        window.nextPhotoId = json.next_id
        window.prevPhotoId = json.prev_id
        photo_div.hide().html(json.photo_rendered).fadeIn("slow")

Is it right way?

ai commented 9 years ago

Use:

$.ajax
      url: url
      success: (json, status, xhr)=>

=> says to CoffeeScript to save this. So callback will have same this as parent block.