加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 如何在Ruby on Rails中创建可用于项目范围的Ja

发布时间:2020-12-16 20:16:56 所属栏目:百科 来源:网络整理
导读:我将以下函数放在我的application.js中: function test() { alert("See Me")} 教室/ _new_small.html.haml: :javascript alert('test'); test(); 在我的application.html.haml中,我使用以下命令: = javascript_include_tag 'application' 我正在得到一个
我将以下函数放在我的application.js中:
function test() {
  alert("See Me")
}

教室/ _new_small.html.haml:

:javascript
  alert('test');
  test();

在我的application.html.haml中,我使用以下命令:

= javascript_include_tag 'application'

我正在得到一个测试,我的firebug控制台中没有定义错误.测试功能是否应该在项目范围内可用,因为它在application.js文件中?谢谢

编辑:我通过javascript渲染页面.会影响吗?

$('#test_container').html("<%= escape_javascript(render :partial => 'classrooms/new_small') %>");

解决方法

假设您正在使用资产管道& coffeescript:不要在application.js中编写代码

为了保持清洁的结构,在app / assets / javascripts中创建一个文件夹(例如:application)

然后在你的application.js中要求它

//= require jquery
//= require jquery_ujs

//= require_tree ./application

创建一个咖啡文件(例如:app / assets / javascripts / application / my_feature.js.coffee

@test = ->
  alert('Hello world')

咖啡输出:

(function() {

  this.test = function() {
    return alert('Hello world');
  };

}).call(this);

最好使用命名空间:

@myGreatFeature =
  test: ->
    alert('Hello world')

或者根据coffeescript常见问题,你可以写

namespace = (target,name,block) ->
  [target,block] = [(if typeof exports isnt 'undefined' then exports else window),arguments...] if arguments.length < 3
  top    = target
  target = target[item] or= {} for item in name.split '.'
  block target,top

namespace 'myGreatFeature',(exports) ->
  exports.test = ->
    alert('Hello world')

那么你可以随时调用myGreatFeature.test()

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读