Question

i have just build a normal RoR 4.1 app, nothing added, to test some coffee script code.

This is the start of the coffee script code

->
  canvas
  ctx
  code
  point
  style
  drag = null
  dPoint
  # define initial points
  Init (quadratic) ->
    point =
      p1:
        x: 100
        y: 250

      p2:
        x: 400
        y: 250

    if quadratic
      point.cp1 =
        x: 250
        y: 100
    else
      point.cp1 =
        x: 150
        y: 100

      point.cp2 =
        x: 350
        y: 100

when rendering in Javascript via the coffee script site it give me that, which seems right

(function() {
  canvas;
  ctx;
  code;
  var canvas, code, ctx, drag;
  drag = null;
  Init(function(quadratic) {
   var point, style;
   point = {
     ...

But when i watch the code generate by rails i see this (and nothing work)

(function() {
    (function() {
        canvas;
        ctx;
        code;
        var canvas, code, ctx, drag;
        drag = null;
        dPoint;
        Init(function(quadratic) {
           .....

do you have any idea what's happened, why is it encapsulated in another function ?

do you need more code ?

best regards

Was it helpful?

Solution

Rails wraps any coffee script in an anonymous function when compiling it, so this is actually valid.

So even something as simple as:

x = 1

in coffeescript, gets compiled to:

(function() {
  var x;
  x = 1;
}).call(this);

In rails javascript. Hence why your sample is compiling to an anonymous function within an anonymous function. Here's the sprockets code that does it:

https://github.com/sstephenson/sprockets/blob/master/lib/sprockets/jst_processor.rb

You could use global variables to get around this, but I wouldn't recommend it, instead, look to create a module system.

OTHER TIPS

Thanks for the answer,

i removed the '->' on top and it works now, it's javascript in an anonymous function.

i wonder what will appends if i write a 'jQuery ->' in top of the script when calling a Jquery plugin, but it seems it as changed since the introduction of turbo-links. but this is another question.

thanks you my current code work now

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top