Javascript coffeescript类-从一个类方法调用另一个类方法

Javascript coffeescript类-从一个类方法调用另一个类方法,javascript,jquery,ruby-on-rails,coffeescript,turbolinks,Javascript,Jquery,Ruby On Rails,Coffeescript,Turbolinks,我已经将rails应用程序中嵌入的JS重写为coffeescript..而且我对coffeescript还是新手 我的方法是这些文章的混合: 我的代码: s = undefined class App.PhotoLike settings: modalElement: $('#myModal') likeButtonId: '#like' photo_id: $('.image_info').attr('photo_id') numberOfLike

我已经将rails应用程序中嵌入的JS重写为coffeescript..而且我对coffeescript还是新手

我的方法是这些文章的混合:

我的代码:

s = undefined
class App.PhotoLike

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

  constructor: (@el) ->
    console.log('constructor called')
    s = @settings
    @bindUIActions()
    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'
这是使用ajax构建的模型的一部分,一旦调用成功,我将创建上述类(的实例):

我的问题。 模态得到加载,一切似乎都很好。但当我触发事件时:

$('#myModal').on 'click', '#like', -> likePhoto()
我得到:

photo.like.self-942fcd8….js?body=1:25 Uncaught ReferenceError: likePhoto is not defined
所以,它不知道likePhoto函数。我试着调用this.likePhoto和@likePhoto,但这是指触发事件的按钮元素

那我该怎么做呢? 欢迎采取其他办法。我不确定我是否需要这些类…但我确实需要结构化代码…

likePhoto()是我们的object/class
App.PhotoLike的函数。你把它叫做局部函数

你可以这样做

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()
  ...

让我知道它是否有效。

基于库马尔的答案,您可以使用粗箭头将
@
绑定到

bindUIActions: =>
  console.log('bindUIActions called')
  $('#myModal').on 'click', '#like', -> @likePhoto()

试试看。

是的……它很有效……太简单了!你能帮我回答一个后续问题吗?我如何让s(设置)变量在classI中按预期工作?对不起,你的预期是什么意思。你想实现什么?我在课程的顶部有一个设置变量,在这里我设置了课程所需的各种设置。因此,我想在类中使用这些设置,例如settings.url,我想您可以直接使用from settings<代码>url='/photos/'+@settings.photo_id+'/like'
。除非您的范围从当前对象更改为窗口或其他任何内容,否则这应该可以正常工作。在这种情况下,您可以在函数顶部创建一个引用this=@
,以供以后使用。希望有帮助。您还可以将设置放入初始化函数中,以确保在初始化对象时这些设置可用。
bindUIActions: =>
  console.log('bindUIActions called')
  $('#myModal').on 'click', '#like', -> @likePhoto()