coffeescript class - 从另一个调用一个 class 方法

coffeescript class - calling calling one class method from an other

我已经将 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 的模型的一部分,一旦调用成功,我就会创建上面的 class(实例):

new (App.PhotoLike)

我的问题。 模态被加载,一切看起来都很好。但是当我触发事件时:

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

我得到:

photo.like.self-942fcd8….js?body=1:25 Uncaught ReferenceError: likePhoto is not defined

所以,它不知道 likePhoto 函数。我试过调用this.likePhoto和@likePhoto,但这指的是触发事件的按钮元素。

那我该怎么做呢? 欢迎使用其他方法。我不太确定我是否需要 classes...但我真的想要结构化代码...

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

如果有效请告诉我。

基于 Kumar 的回答,您可以使用粗箭头将 @ 绑定到 this:

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

试试看。