简体   繁体   中英

Javascript functions in the rails 4 asset pipeline tree

I'm trying to utilize a javascript function via the Chrome Console when I put that javascript function within the Rails Asset Pipeline Manifest. Here are the steps I've take to create and setup a simple Rails 4.2.4 App

$ rails new JavascriptExample
$ cd JavascriptExample
$ rails g scaffold Bear name:string
$ rake db:migrate

I then edit the app/assets/javascripts/bears.coffee and add a console log and a function.

console.log("asset pipeline sucks")
square = (x) -> x * x

Then I fire up the server

$ rails s

I visit localhost:3000/bears and in the Chrome Console I see that my first line of code has worked. However when I attempt the command square(5); in console I receive an error Uncaught ReferenceError: square is not defined(…)

Why can I not do it this way when this function is clearly loaded into application.js ?

This is what your coffeescript was compiled to javascript

(function() {
  var square;

  console.log("asset pipeline sucks");

  square = function(x) {
    return x * x;
  };
}).call(this);

From this : the var keyword is reserved in CoffeeScript, and will trigger a syntax error if used. Local variables are created implicitly by default the var keyword is reserved in CoffeeScript, and will trigger a syntax error if used. Local variables are created implicitly by default , so it is not available in global scope as your expectation

To make it work, we can do something like this instead:

console.log("asset pipeline sucks")
@square = (x) -> x * x

Note that we have @ And now the compiled javascript will be:

(function() {
  console.log("asset pipeline sucks");

  this.square = function(x) {
    return x * x;
  };

}).call(this);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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