RubyRedGrapefruit
RubyRedGrapefruit

Reputation: 12224

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.

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.

I converted this to CoffeeScript as the following:

# 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. 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". I am definitely no JS/CoffeeScript expert though, which is the reason for my question.

Upvotes: 0

Views: 90

Answers (1)

Javier Buzzi
Javier Buzzi

Reputation: 6818

  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})

Upvotes: 1

Related Questions