简体   繁体   English

.js.erb VS .js

[英].js.erb VS .js

What is the advantage to putting you javascript for your rails app into a .js.erb file instead of just throwing it in your application.js file? 将你的rails应用程序的javascript放入.js.erb文件而不是将其放入application.js文件中有什么好处? I have a create button for businesses so should I put the code into a create.js.erb file or put it into my application.js using: 我有一个企业的创建按钮,所以我应该将代码放入create.js.erb文件或将其放入我的application.js使用:

$("#business_submit").click(function() {}

All that aside is that I have my create button 除此之外,我有我的创建按钮

    $('.error').hide();
$("#business_submit").click(function() {
    // validate and process form here

    $('.error').hide();
    var name = $("input#business_name").val();
    if (name == ""  || name == "Required Field") {
        $('#namelabel').show()
        $("#business_name").focus();
        return false;
    }
    var address = $("#business_address").val();
    if (address == ""  || address == "Required Field") {
        $('#addresslabel').show();
        $("#business_address").focus();
        return false;
    }
    var city = $("#business_city").val();
    if (city == "" || city == "Required Field") {
        $('#citylabel').show();
        $('#business_city').focus();
        return false;
    }
    var state = $("#business_state").val();
    if (state == ""  || state == "Required Field") {
        $('#statelabel').show();
        $("#business_state").focus();
        return false;
    }
    var zip = $("#business_zip").val();
    if (zip == ""  || zip == "Required Field") {
        $('#ziplabel').show();
        $("#business_zip").focus();
        return false;
    }
    var phone = $("#business_phone").val();
    if (phone == ""  || phone == "Required Field") {
        $('#phonelabel').show();
        $("#business_phone").focus();
        return false;
    }

     var category = $("#business_business_category_id").val();
    if (category == " - Choose one - ") {
        $('#categorylabel').show();
        $("#business_business_category_id").focus();
        return false;
    }
    $("#new_business")[0].reset();
    $("#new_business").toggle();
   return false;
});

This works great in my .js file but when I click create it doesn't actually send the information they typed in the form to the database. 这在我的.js文件中效果很好但是当我点击创建时它实际上并没有将他们在表单中输入的信息发送到数据库。 So I tried copy pasting the code into the .js.erb file. 所以我尝试将代码复制粘贴到.js.erb文件中。 Now the form is submitted to the database when I click create, but half the javascript isn't working. 现在,当我单击“创建”时,表单将提交到数据库,但是一半的javascript无法正常工作。 The $('.error').hide(); $('。error')。hide(); isn't hiding my errors and they are all showing up regardless. 没有隐藏我的错误,他们都出现了。 $("#new_business")[0].reset(); $( “#new_business”)[0] .reset段(); isn't reseting my form, and there is no validation checks when I click create. 没有重置我的表单,单击创建时没有验证检查。 So I either have a fully functional form that doesn't submit or one that submits but isn't really functional. 所以我要么有一个功能齐全的表单,不提交,要么提交但不是真正的功能。 Which one should I try to get working? 我应该尝试哪一个工作?

I see a lot of code with $.ajax but I can't figure it out for the life of me. 我看到很多带有$ .ajax的代码,但是我无法理解我的生活。 I tried for a bit and I started getting some forgery protection errors in rails which is a whole other problem. 我尝试了一下,我开始在rails中获得一些伪造保护错误,这是另一个问题。

.js.erb files are for controller actions, such as create, when you want javascript to be executed when the action completes. 当您希望在操作完成时执行javascript时, .js.erb文件用于控制器操作,例如create。 For example, when you want to submit a form via ajax and want display an alert when everything is done, you would put the 例如,当您想通过ajax提交表单并希望在完成所有操作后显示警告时,您可以将其设置为

$('#business_submit').click(...)

in your application.js or *.html.erb, and your create.js.erb could look like this: 在您的application.js或* .html.erb中,您的create.js.erb可能如下所示:

alert('New object id: ' + <%= new_object.id %>);

This way, the javascript that is getting returned to the browser can be first rendered by Erb, allowing you to insert custom strings/variables/etc just like you can in .html.erb templates. 这样,返回到浏览器的javascript可以首先由Erb呈现,允许您像在.html.erb模板中一样插入自定义字符串/变量/等。

If I may contribute to the answer with my few cents... 如果我可以用我的几分钱为答案做出贡献......

The answer to your question is really simple : 你的问题的答案非常简单:

  • A file ending with *.js.erb allows your file to be interpreted by ruby . * .js.erb结尾的文件允许您的文件由ruby解释 (So you will be able to use rails helpers) (所以你将能够使用铁路助手)

  • A file ending with *.js is a pure javascript . * .js结尾的文件是纯JavaScript

You will never get a *.js file to work if you place any ruby code inside like: 如果你在里面放置任何ruby代码,你永远不会得到一个* .js文件:

$(function () {
  new Highcharts.Chart({
    chart: { renderTo: 'orders_chart' },
    title: { text: <%= gon.my_title_of_the_day.to_json %> },
  });
})

The part <%= gon.my_title_of_the_day.to_json %> will just generate an error because javascript knows nothing about ruby. 部分<%= gon.my_title_of_the_day.to_json %>只会生成错误,因为javascript对ruby一无所知。

In order your *.js file works, you will have to statically change it every time the day changes: 为了使您的* .js文件正常工作,您必须在每次更改时静态更改它:

$(function () {
  new Highcharts.Chart({
    chart: { renderTo: 'orders_chart' },
    title: { text: 'Monday' },
  });
})

NB : If you use a *.js.erb, you will need in addition the " Gon " gem to pass data from your controller to JS though. 注意 :如果您使用* .js.erb,您还需要“ Gon ”gem来将数据从控制器传递给JS

Now for your underlying question "why is my javascript code not working '" I can't answer because I'm no javascript expert and this is another story... ;-) 现在你的基本问题是“为什么我的javascript代码无法运行”我无法回答,因为我不是javascript专家,这是另一个故事...... ;-)

Per my view, the reason to have js.erb files is to gain access to rails helpers like the something_url routes. 根据我的观点,拥有js.erb文件的原因是为了获得像something_url路由这样的rails helper。 I've found, most of the time, that those URLs are already embedded in the <form> tag or something like that, so I have little need for it. 我发现,大多数时候,这些URL已经嵌入在<form>标签或类似的东西中,所以我几乎不需要它。 Processing everything with .erb also prevents you from caching javascript as aggressively. 使用.erb处理所有内容也会阻止您积极地缓存javascript。

For those reasons, I think the most appropriate decision is to put javascript in the most unobtrusive place possible: application.js (or other static scripts). 出于这些原因,我认为最合适的决定是将javascript放在最不显眼的地方:application.js(或其他静态脚本)。 Especially with jQuery, that's really as it was intended. 特别是对于jQuery,这真的是它的意图。

By the way, javascript_auto_include is a nice, tidy plugin for organizing your javascript according to the views that are rendered. 顺便说一句, javascript_auto_include是一个漂亮,整洁的插件,用于根据渲染的视图组织您的JavaScript。 Rather than stashing everything in application.js , you might consider this. 您可以考虑这一点,而不是在application.js所有内容。

js.erb versus js.rjs js.erb与js.rjs

One of these two ( .erb ) is really for generating javascript from a template. 这两个中的一个( .erb )实际上是用于从模板生成javascript。 This is the sort of thing you would include as a tag in the HTML. 这是您在HTML中作为标记包含的内容。 The other ( .rjs ) is about controlling page content in an AJAX response, and would not be run until such an AJAXy call was made. 其他( .rjs )是关于控制AJAX响应中的页面内容,并且在进行这样的AJAXy调用之前不会运行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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