The problem is that the value of this
(AKA @
in CoffeeScript) inside a function depends on how the function is called unless you've bound the function to a specific object. You're doing this to bind the function to an event:
$(window).on('resize', this.changePosition)
jQuery's on
will set this
to window
when calling changePosition
in this case:
When jQuery calls a handler, the this
keyword is a reference to the element where the event is being delivered; for directly bound events this is the element where the event was attached and for delegated events this is an element matching selector
.
If you want this
to be the view then use a fat-arrow (=>
) when defining the method:
changePosition: =>
@tryPrint()
Other options:
Use a bound function:
$(window).on('resize', @changePosition.bind(@))
$(window).on('resize', _(@changePosition).bind(@))
$(window).on('resize', $.proxy(@changePosition, @))
#...
Manually set this
:
that = @
$(window).on('resize', -> that.changePosition())
Using =>
is probably the easiest as you'll want to off
the handler when destroying your view and =>
will keep function references right.