Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Referencing parent class in CoffeeScript from a jQuery callback

I'm new to CoffeScript and I was wondering if there's a way of writing the following piece of code without referencing the global variable app:

class App 

    constructor: ->
        @ui = ui.init()
        $('#content-holder a[rel!=dialog]').live 'click', ->
            link = $(@).attr 'href'
            app.loadUrl link
            return false

    loadUrl: (href) ->
        # ...

app = new App()

Using the fat arrow doesn't work, as then I lose reference to the jQuery object, i.e.

class App   
    constructor: ->
        @ui = ui.init()
        $('#content-holder a[rel!=dialog]').live 'click', =>
            # @ now references App
            link = $(@).attr 'href'
            this.loadUrl link
            return false

    loadUrl: (href) ->
        # ...

The first piece of code works, but I want to get rid of the global variable if possible :-)

Cheers, Gaz.

like image 834
Gaz Avatar asked Oct 10 '11 18:10

Gaz


2 Answers

Your click handler gets an event passed in... so you can get the best of both worlds with the "fat arrow" without the need to also reference self :

constructor: ->
    @ui = ui.init()
    $('#content-holder a[rel!=dialog]').live 'click', (e) =>
        link = $(e.target).attr 'href'
        @loadUrl link
        return false
like image 62
Brian Genisio Avatar answered Nov 02 '22 03:11

Brian Genisio


Well, CS is just a higher-level syntax for JS.

In JS this can only reference a single object.

The fat arrow uses closure to make this equal to a higher level this, nothing more, and that's why it overrides this in a callback's scope

The plain arrow, in contrary, is just a function alias, and that's why this is a DOM element in the first case.

Finally, @something is trivially translated to this.something, and does nothing more.

So, my opinion - your best choice is really doing self = @ before the binding.

like image 38
Guard Avatar answered Nov 02 '22 04:11

Guard