0
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.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
Farzher
  • 13,934
  • 21
  • 69
  • 100

1 Answers1

1

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.

elclanrs
  • 92,861
  • 21
  • 134
  • 171