一组可供 Rails 应用程序使用的 CoffeeScript/JavaScript 类和方法 [英] Set of CoffeeScript/JavaScript classes and methods available to rest of Rails app

查看:24
本文介绍了一组可供 Rails 应用程序使用的 CoffeeScript/JavaScript 类和方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I'm using Rails 3.2.9. When I add CoffeeScript code to a .js.coffee file in the /app/assets/javascripts directory, I get the resulting JavaScript in all of my webpages. The problem is all the JavaScript is wrapped in:

(function() {
  // my code
}).call(this);

So any methods I define are not visible in any other CoffeeScript code I write in other files. What's the proper way to write a set of reusable CoffeeScript classes and methods with Rails?

解决方案

The simplest thing to do is to namespace all your classes. If your application is called "app" then in your initialization code before anything else happens:

// Set up the namespace.
window.app = { }

and then in all your .coffee files:

class app.Pancakes
    #...

Then you'd have a global namespace and you'd reference everything through that namespace:

pancakes = new app.Pancakes

Similarly for simple functions:

app.where_is = (pancakes, house) -> ...

# And elsewhere...
x = app.where_is(...)

There are various ways of setting up and partially hiding the namespace but they're all variations on the above and simple namespacing plays nicely with the Rails asset pipeline.

这篇关于一组可供 Rails 应用程序使用的 CoffeeScript/JavaScript 类和方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆