martin martin - 2 years ago 96
Javascript Question

coffeescript class - calling calling one class method from an other

I have rewritten my embedded JS in my rails app to coffeescript..and I am new to coffeescript...

My approach is a mix of these articles:

My code:

s = undefined
class App.PhotoLike

modalElement: $('#myModal')
likeButtonId: '#like'
photo_id: $('.image_info').attr('photo_id')
numberOfLikes: $('#likes_num')

constructor: (@el) ->
console.log('constructor called')
s = @settings
return this

bindUIActions: ->
console.log('bindUIActions called')
$('#myModal').on 'click', '#like', -> likePhoto()
$(document).on "page:change", -> pageChange()

pageChange: ->
console.log('pageChange called')
photo = new App.Photo

likePhoto: ->
console.log('likePhoto called')
url = '/photos/' + s.photo_id + '/like'
$.get url, (data) ->
s.numberOfLikes.html data['likes'] + ' likes'
$(s.likeButtonId).toggleClass 'btn-success'

This is part of a model that gets loded with ajax and once that call succeeds i do i create the above class (instance of):

new (App.PhotoLike)

My problem.
The modal gets loaded an all seems good. But when I trigger the event:

$('#myModal').on 'click', '#like', -> likePhoto()

I get:….js?body=1:25 Uncaught ReferenceError: likePhoto is not defined

so, it does not know the likePhoto function. I have tried calling this.likePhoto and @likePhoto, but this refers to the button element that triggers the event.

So how do I do this?
Other approaches are welcome. i not really sure that I need the classes...but I really want structured code...

Answer Source

likePhoto() is a function of our object/class App.PhotoLike. And you're calling it like a local function.

You can do something like this instead

bindUIActions: ->
  _this = this #this will change inside, so we have to have a reference to our object here
  console.log('bindUIActions called')
  $('#myModal').on 'click', '#like', -> _this.likePhoto()

Let me know if it works.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download