简体   繁体   English

如何使该CoffeeScript对象工作?

[英]How can I make this CoffeeScript object work?

I'm learning to use a small library called Bootbox in my Twitter Bootstrap -enabled Rails v4.2 application. 我正在学习在启用Twitter Bootstrap Rails v4.2应用程序中使用一个名为Bootbox的小型库。

There are several examples on the main page in order to test some of the functionality. 主页上有几个示例,以测试某些功能。 In these examples they reference a small JS file that contains an object called Example . 在这些示例中,他们引用了一个小的JS文件,其中包含一个名为Example的对象。

I converted this to CoffeeScript as the following: 我将其转换为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

There is no issue with the actual Bootbox functionality. 实际的Bootbox功能没有问题。 However, I can see an error in the console when I click the button that within the dialog box: 但是,单击对话框中的按钮时,我会在控制台中看到错误:

Uncaught TypeError: Example.show is not a function

It seems pretty clear, I thought, that I have set up an object Example with a class method called "show". 我认为,似乎很清楚,我已经用一个名为“ show”的类方法建立了一个对象Example I am definitely no JS/CoffeeScript expert though, which is the reason for my question. 我绝对不是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})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM