如何将CoffeeScript文件与视图相关联? [英] How do I associate a CoffeeScript file with a view?

查看:115
本文介绍了如何将CoffeeScript文件与视图相关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

刚刚安装rails 3.1 rc1,我试图grok使用新的资产管道管理javascript的最佳方式
默认情况下,所有coffeescript被编译成一个application.js文件,这是一件好事。

Just installed rails 3.1 rc1 and am trying to grok the best way to manage javascript with the new asset pipeline By default all coffeescript is compiled into a single application.js file, this is a good thing.

每个独立的咖啡脚本文件附加到js文件中,并包含在通过调用方法
执行的匿名函数中。常见的情况是使用一些jquery将各种形式转换为ajax形式,更新UI等...

Each seperate coffee script file is appended to the js file and wrapped in an anonymous function which is executed via the call method A common scenario would be to use some jquery to turn various forms into ajax forms, update UI, etc...

许多脚本将特定于控制器或操作,我试图grok '常规的'处理方式,
,因为一切都包装在一个匿名函数中,我如何只执行
的代码为一个特定的控制器/动作,默认情况下所有的匿名函数正在执行

Many of these scripts will be specific to a controller or action, I am trying to grok the 'conventional' way to handle this, since everything is wrapped in an anonymous function how do I only execute just the code for a particular controller / action, by default all of the anonymous functions are being executed

我玩过一些hacks,我把控制器和动作名称加载到js变量,然后在
coffeescript检查那些有条件地运行代码,我don非常喜欢

I did play around with some hacks where I load the controller and action name into js variables and then in coffeescript check those to conditionally run code, I don't like that very much

我最初的想法是每个咖啡文件将包含一个js命名空间/对象,我会调用特定的视图,
使用default_bare = true配置spike this

my initial thought was that each coffee file would contain a js namespace/object and I would call the specific ones from the view, going to spike this using the default_bare = true configuration

请参阅

see How can I use option "--bare" in Rails 3.1 for CoffeeScript?

EDIT

一些更多:这看起来可能是正确的方法 - 找不到变量错误与Rails 3.1和Coffeescript

Looking around some more: this looks like it might be the correct approach - "Can't find variable" error with Rails 3.1 and Coffeescript

推荐答案

有两种常见的方法:


  1. 使行为以存在特定元素为条件。例如,运行注册表的代码应该以

  1. Make behavior conditional on the presence of a particular element. For instance, code to run a signup sheet should be prefaced with something like

开头,如果$('#signup')。 0

if $('#signup').length > 0

使行为以 body 元素上的类为条件。您可以使用ERB设置body类。这通常也适用于样式表。代码将是

Make behavior conditional on a class on the body element. You can set the body class using ERB. This is often desirable for stylesheets as well. The code would be something like

if $('body')。hasClass'user'

这篇关于如何将CoffeeScript文件与视图相关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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