如何在coffeescript中从扩展类调用方法

如何在coffeescript中从扩展类调用方法,coffeescript,Coffeescript,这是我第一次在coffeescript中使用继承 我试图从扩展类中调用方法,但方法@create from window.StreamingStation提供了此功能。create不是函数 class window.BaseClass constructor: (options) -> @key = options['key'] @content_id = null @rtapi = options['rtapi'] @switch = $('input

这是我第一次在coffeescript中使用继承

我试图从扩展类中调用方法,但方法@create from window.StreamingStation提供了此功能。create不是函数

class window.BaseClass
  constructor: (options) ->
    @key = options['key']
    @content_id = null
    @rtapi = options['rtapi']
    @switch = $('input[name="activate_autodj"]')
    @setup()

class window.StreamingStation extends window.BaseClass
  constructor: (options) ->
    super

  list: () ->
    $.ajax
      url: @rtapi + '/api/StreamingStation/list'
      type: 'get'
      data:
        query:
          data:
            contentId: @content_id
          token: @key
      success: (data) ->
        console.log(data)
    return

  create: () ->
    alert 'fsafsa'
    return

class window.AutoDj extends window.StreamingStation

  constructor: (options) ->
    super

  setup: ->
    @bindings()
    @activateAutoDj()

  bindings: () ->
    $('input[type="checkbox"]').bootstrapSwitch({size: 'mini'});

  activateAutoDj: () ->
    $('input[data-id]').on 'switchChange.bootstrapSwitch', (event, state) ->
      @create()
      state = (state == true ? 1 : 0)
      @content_id = $(this).attr('data-id')
      $.ajax
        url: "/autodjs/#{@content_id}/activate_autodj"
        type: 'post'
        data: {state: state}
        async: true
        success: (data) ->
          if (data.error == 0)
          else
            @raiseSystemAlert(data.message)
        error: (data) ->
          @raiseSystemAlert('Unexpected error, Please try again.')

  raiseSystemAlert: (message) ->
    modal = $('#systemAlertModal')
    modal.find('.modal-body').html(message)
    modal.modal('show')

提前感谢大家

问题似乎出现在您在activateAutoDj方法中声明的事件处理程序函数中:

因为您使用的是一个瘦/刺箭头,所以事件处理程序的this上下文将不是AutoDj实例的this上下文;事实上,它将是调用方决定的任何对象,在本例中,如果我没有弄错的话,它将是引发事件的对象

解决此问题的一种方法是强制事件处理程序函数使用fat/hashrocket=>箭头绑定到此上下文

或者,正如您所指出的,另一种方法是使用闭包来保存父函数的上下文。正如您所指出的,您只需执行以下操作:

cls = @ # preserving the `this` context
$('input[data-id]').on 'switchChange.bootstrapSwitch', (event, state) -> 
  cls.create()
  # rest of function

我做coffeescript已经有一段时间了,但乍一看,您似乎并没有绑定到…“switchChange.bootstrapSwitch”中的this上下文。。。事件处理程序。尝试对函数使用胖箭头/hash rocket=>。让我知道这是否有效。@是这样吗@create等于这个。create是这样的。但是事件处理程序正在被异步调用,它的this上下文将不是AutoDj实例的this上下文。@PaulRichter您的权利!令人惊叹的我会找一个解决办法。酷。那我就把它作为一个答案。
cls = @ # preserving the `this` context
$('input[data-id]').on 'switchChange.bootstrapSwitch', (event, state) -> 
  cls.create()
  # rest of function