0

I have a problem with the "this" reference on Backbone with Coffeescript, this is a method which shows information of an artist:

show: (id) ->
    self = @
    if @collection
        artist = @collection.get(id)
        @renderArtist(artist)
    else
        artist = new DemoBackbone.Models.Artist({id: id})
        artist.fetch
            success: ->
                self.renderArtist(artist)

renderArtist: (artist) ->
    view = new DemoBackbone.Views.ArtistsShow(model: artist)
    $('#content_artists').html(view.render().el)

This works perfectly, but I'm using the "self = @" statement so I can use the Class function "renderArtist", but is there a more "elegant" way to do this on "success: -> self.renderArtist(artist)", so I can avoid using the "self = @" line??

Something like

success: @->
    @renderArtist(artist)

I'm not pretty sure but I think there should be a way to do this. Thanks

4

1 回答 1

2

这正是CoffeeScript 中的双箭头函数所做的。它将自动生成您为您展示的代码,因此您不必自己编写。

success: =>
    @renderArtist(artist)
于 2013-04-20T20:01:02.220 回答