Search code examples
livescript

LiveScript class scope this self jquery issues


class A
    () ->
    method: ->
    method2: ->
        $ 'a' .each ->
            href = $ @ .attr 'href'
            @method href

In my jQuery function I actually need both scopes, so I can't just change how the anonymous function is bound. I could put at the beginning of method2 self = @ and then use self.method. I'd like to always use self.method. But I'd rather not put that at the beginning of every function.

Is there anyway to set up self in the constructor to always exist and point to @? Everything I tried failed. self was always undefined in the methods.

I put Coffeescript as a tag because it's very similar to LiveScript.


Solution

  • The wavy arrow ~> lets you carry down the context so you can avoid self = @:

    method2: ->
      $ \a .each (, el) ~>
        href = $ el .attr \href
        @method href
    

    Pass the jQuery element in the callback as a parameter and keep using the wavy arrow so the context will always be the instance.