如何使此CoffeeScript对象工作

How can I make this CoffeeScript object work?

本文关键字:工作 对象 CoffeeScript 何使此      更新时间:2023-09-26

我正在学习在启用了Twitter BootstrapRails v4.2应用程序中使用一个名为Bootbox的小型库。

主页上有几个示例来测试一些功能。在这些示例中,它们引用了一个小型JS文件,该文件包含一个名为Example的对象。

我将其转换为CoffeeScript,如下所示:

# Place all the behaviors and hooks related to the matching controller here.
# All this logic will automatically be available in application.js.
# You can use CoffeeScript in this file: http://coffeescript.org/
jQuery ->
  ###*
  # This tiny script just helps us demonstrate
  # what the various example callbacks are doing
  ###
  Example = ->
    'use strict'
    elem = undefined
    hideHandler = undefined
    that = {}
    that.init = (options) ->
      elem = $(options.selector)
      return
    that.show = (text) ->
      clearTimeout hideHandler
      elem.find('span').html text
      elem.delay(200).fadeIn().delay(4000).fadeOut()
      return
    that
  $("#search-link").click ->
    bootbox.dialog
      message: 'I am a custom dialog'
      title: 'Custom title'
      buttons:
        success:
          label: 'Success!'
          className: 'btn-success'
          callback: ->
            Example.show 'great success'
            return

实际的Bootbox功能没有问题。然而,当我点击对话框中的按钮时,我可以在控制台中看到一个错误:

Uncaught TypeError: Example.show is not a function

我想,似乎很清楚,我已经用一个名为"show"的类方法设置了一个对象Example。不过,我绝对不是JS/CoffeeScript专家,这也是我提出这个问题的原因。

  Example = (->
    'use strict'
    elem = undefined
    hideHandler = undefined
    that = {}
    that.init = (options) ->
      elem = $(options.selector)
      return
    that.show = (text) ->
      clearTimeout hideHandler
      elem.find('span').html text
      elem.delay(200).fadeIn().delay(4000).fadeOut()
      return
    that
 )()
 Example.init({selector: JQUERY_SELECTOR})