0

I would like to use a jQuery element in an iterative function, while maintaining access to a class' instance variables.

For example:

class MyClass

  myVar: true

  myFunction: =>
    $('div').each ->
      console.log @.myVar # true?
      console.log $(this) # div?
1
  • @tymeJV No, the code doesn't look fine at all.. Commented Oct 28, 2013 at 19:14

1 Answer 1

2

The answer to the question you asked is: Use the fat arrow with each to maintain the value of @, and use the index/element arguments being passed to each to access the element:

myFunction: =>
  $('div').each (i, e) =>
    console.log @myVar
    console.log $(e)

Also, use @myVar instead of @.myVar (both will work, but @.myVar is far from idiomatic).

The better answer to what you're actually trying to do is, avoid each and use CoffeeScript's for/in:

myFunction: ->
  for div in $('div')
    console.log @myVar # true
    console.log $(div) # div
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.