3

Trying to find out best approach to have this work:

class Person

  constructor: (@el) ->
    @el = $(el)
    this.bind()

  bind: ->
    @el.find('.something').on 'click', ->
      $(this).hide()       # conflict!
      this.do_something()  # conflict!

  do_something: ->
    alert 'done!'

I'm aware I can use the hash rocket (=>) and then access this.do_something from within my callback, but then that conflicts with callback 'this', and so jquery is trying to select object, not element '.something'. How to resolve this?

1 Answer 1

3

You can't get this to refer to different objects. Use a different identifier, by storing the instance's this reference in an auxiliary variable:

  bind: ->
    person = this
    @el.find('.something').on 'click', ->
      $(this).hide()
      person.do_something()
Sign up to request clarification or add additional context in comments.

4 Comments

That's the best approach? Thanks btw.
@Zenph Yes, that's the best (most readable) approach. You cannot use this to point to different objects in the same context.
I understand context ;) Was hoping either CS or jQuery had a proxy variable to this for such conflicts.
It works but is still annoying, I wish CoffeeScript classes used something like self rather than this!

Your Answer

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