Rails: JS Controller Being Called Twice for Some Reason

匿名 (未验证) 提交于 2019-12-03 03:08:02

问题:

For some reason when I click on a button, my controller and the resulting jquery function gets called twice. Since the js function being called is toggle, this is a problem as it causes the code to jump in and out of view.

Here is the form:

Unseen Notifications: <%=  current_user.notification_unseen %> </div>                 <%= button_to "show", {:action => "seen", :controller=>"notifications"}, :remote => true %> 

Here is the controller:

def seen     respond_to do |format|       format.js      end   end 

Here is the jquery:

$("div#notifications").toggle(); $("div#count").html("<%= escape_javascript( render :partial => 'notifications/count')%>"); 

I am at a loss for why on earth this would possibly happen. I have been very careful not to double click and don't know how to prevent it. Any suggestions would be greatly appreicated.

回答1:

I had a recent problem like this before, when I had 2 jquery libraries included. In particular, check that you only have jquery_ujs.js and not jquery.js. Seems like when you include both of them certain js functions are called twice.

Hope this helps!



回答2:

If Benjamin's suggestion doesn't work, you could go with cheats and hacks and add 1 to some global var on each click (which would happen twice), then use modulus to only trigger your action when (global_counter % 2 == 0).

Just to be clear, this is a terrible solution that you should avoid using if at all possible...



回答3:

I'm new to rails and had the same problem. It turns out I had:

<%= javascript_include_tag "application" %>

In both my view and in application.html.erb. I removed one of them and voila, fixed.



回答4:

Taking the jquery_ujs.js worked for me.

Take a close look at the file application.html.erb to see if that is referring to jquery.js and jquery_ujs.js. If so, just take the jquery_ujs.js out, refresh the browser and try it again.

Also, take a look at the page source and see if jquery_ujs and jquery is referred to at the same time. If so, search in the source files for references to that jquery_ujs.

Worked for me, thanks guys.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!