如何处理JavaScript事件(例如'link_to:remote')的Rails方式? [英] How to handle JavaScript events (e.g. 'link_to :remote') the Rails Way?
问题描述
我正在使用Ruby on Rails 4,我想以Rails的方式处理JavaScript事件。也就是说,例如,给定我有以下
I am using Ruby on Rails 4 and I would like to handle JavaScript events the Rails way. That is, for example, given I have the following
link_to('destroy', article_path(@article), :method => :delete, :remote => true)
当我点击上面生成的链接然后我希望 success
JS事件通过删除已删除的文章DOM元素来更新页面内容。应该忽略AJAX响应,无论它是什么。
when I click on the above generated link then I would like the success
JS event to update the page content by removing the deleted article DOM element. The AJAX response, whatever it is, should be ignored.
我知道 rails.js 文件,但我不知道如何使用它来完成我要找的东西。
I am aware of the existence of the rails.js file but I don't how to use it in order to accomplish what I am looking for.
推荐答案
有一个wiki页面 https://github.com/rails/jquery-ujs/wiki/ajax ,附有ujs自定义事件的说明。以下是一个小例子:
There is a wiki page https://github.com/rails/jquery-ujs/wiki/ajax with explanation of ujs custom events. Here is a little example in your case:
$('a').on 'ajax:success', -> alert 1
UPD 如果要阻止评估XHR响应,请添加 data-type = text
远程链接的属性:
UPD If you want to prevent XHR response being evaluated, add data-type=text
attribute to your remote link:
link_to('destroy', article_path(@article), :method => :delete, :remote => true, 'data-type' => 'text')
这篇关于如何处理JavaScript事件(例如'link_to:remote')的Rails方式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!