Search code examples
ruby-on-railscoffeescripterb

Calling CoffeeScript method defined in another file form within an erb template


Shouldn't I be able to call this CoffeeScript method from within an erb template? It's not working but it seems like it should.

setup.js.coffee

class SetupStepTwo

  include @

  constructor: ->
    @resetView()

  resetView : ->
    console.log('cool');

window.ns1.SetupStepTwo = SetupStepTwo

$ ->
  new SetupStepTwo()

update.js.erb

window.ns1.SetupStepTwo.resetView();

Solution

  • Your SetupStepTwo class has an instance method called resetView but you're trying to call it as a class method (or at least what passes as a class method in (Java|Coffee)Script) when you say this:

    window.ns1.SetupStepTwo.resetView();
    

    If you really want to use resetView as a class method then your class should look more like this:

    class SetupStepTwo
      constructor: ->
        @constructor.resetView()
    
      @resetView : ->
        console.log('cool')
    

    The @ on @resetView makes a class method and @constructor is, more or less, like self.class in Ruby.

    Demo: http://jsfiddle.net/ambiguous/eDdmd/

    If you want resetView to be an instance method then you'll need to replace this:

    window.ns1.SetupStepTwo.resetView();
    

    with a resetView call on an instance of SetupStepTwo.