1

I'm trying to get a function into the asset pipeline in coffeescript

If I use pure javascript,

mymodel.js

function restrictPlayback(event) {
   // Trying to stop the player if it goes above 1 second
   if (event.currentTime > 10) {
     event.pause();
     event.currentTime = 0
   }
 }

This compiles fine and the function works.

If I put the following:

mymodel.js.coffee

restrictPlayback = (event) ->

  # Trying to stop the player if it goes above 10 seconds
  if event.currentTime > 10
    event.pause()
    event.currentTime = 0

I get the following error

Uncaught ReferenceError: restrictPlayback is not defined

What am I doing wrong?

4
  • I don't write Coffeescript but I put your JS into js2coffee and it has a return statement at the end of the function. It also depends on where you're trying to access restrictPlayback. Commented Jan 6, 2016 at 16:24
  • 1
    The issue is not related to the code you gave us. Your CoffeeScript compiles fine. Commented Jan 6, 2016 at 16:25
  • Where are you calling restrictPlayback? If it's before you declare it, that's likely what the issue is Commented Jan 6, 2016 at 23:18
  • I'm trying to put it in the asset pipeline. If I put recordings.js as a file, this merges into application.js fine. If I put it as recordings.js.coffee as a coffeescript file, it doesn't work anymore. Possibly the issue is that my application.js is exactly that. application.js, not application.js.coffee... Commented Jan 6, 2016 at 23:54

1 Answer 1

1

I suspect that you're defining the function and then expecting it to have global scope (i.e. usable from anywhere).

By default, Coffeescript wraps compiled code into Immediately Invoked Function Expressions (IIFEs) so the function you declared is only valid within the scope of the Coffeescript file.

You can get Coffeescript to stop wrapping in IIFEs by using the -b flag when compiling although it's much better practice to learn to do things the Coffeescript way.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.