提问人:James P McGrath 提问时间:9/28/2011 更新时间:9/28/2011 访问量:3979
Rails 3.1 远程按钮未捕获 Unobtrusive Javascript 事件 (JQuery)
Rails 3.1 Remote Button Unobtrusive Javascript event not caught (JQuery)
问:
我想开始使用 Ajax 事件 ajax:success、ajax:failure、ajax:complete 和 ajax:beforeSend,因为在以下帖子中推荐用于不显眼的 Javascript:
- http://www.simonecarletti.com/blog/2010/06/unobtrusive-javascript-in-rails-3/
- http://www.alfajango.com/blog/rails-3-remote-links-and-forms/
但出于某种原因,它对我不起作用。我错过了一些东西(一些小东西),因为我无法让事件触发我的 Javascript。我希望有人能发现我的代码中的“明显”错误/遗漏。
关于我的环境的一些细节:
- 轨道 3.1
- jQuery (jquery-rails gem)
- 用于服务器端 JS 处理的 Rubyracer(对于我的例子来说并不重要)
为了尝试找出我缺少的东西,我创建了一个简单的测试应用程序,它有一个远程按钮。单击该按钮时,我希望触发警报框。这个应用程序的代码可以在 github 上看到:
http://github.com/jpmcgrath/rbtest
我在这里将应用程序部署到 heroku:
http://rbtest.heroku.com/projects/
如果你看一下应用程序,你可以点击按钮,按钮成功创建一个新项目(看到它手动刷新),但ajax:success事件似乎没有发生?
代码的内涵如下:
在 projects_controller.rb 中
def remote_test
@project = Project.new(:name => "remote test")
respond_to do |format|
if @project.save
puts "project saved!\n\n\n"
format.html { redirect_to @project, notice: 'Project was successfully created.' }
format.json { render json: @project, status: :created, location: @project }
else
format.html { render action: "new" }
format.json { render json: @project.errors, status: :unprocessable_entity }
end
end
end
在应用程序.js中
jQuery(document).ready(function() {
jQuery(".remote_button").click(function() {
alert('Handler for .click() called.');
})
.bind("ajax:complete", function() {
alert('complete!');
})
.bind("ajax:beforeSend", function () {
alert('loading!');
})
.bind("ajax:error", function (xhr, status, error) {
alert('failure!');
})
.bind('ajax:success', function(event, data, status, xhr) {
alert('success!');
});
});
在视图 projects/index.html.erb 中
<%= button_to "remote test", remote_test_path, :remote => true, :class => 'remote_button' %>
如果有人能指出我遗漏了什么(我怀疑这与响应类型有关),将不胜感激。
答:
Rails 改变了 javascript 文件的处理方式。
Railscasts 有几个例子。
http://railscasts.com/episodes/279-understanding-the-asset-pipeline
http://railscasts.com/episodes/267-coffeescript-basics?autoplay=true
评论
事件处理程序未触发的原因是选择器位于错误的元素上。button_to创建一个具有单个输入标记的表单,并且该输入标记具有您选择的类,但 ajax 事件是在表单上触发的,而不是在输入标记上触发的。
试试这个
jQuery(document).ready(function() {
jQuery(".remote_button").click(function() {
alert('Handler for .click() called.');
});
jQuery("form.button_to").bind("ajax:complete", function() {
alert('complete!');
})
.bind("ajax:beforeSend", function () {
alert('loading!');
})
.bind("ajax:error", function (xhr, status, error) {
alert('failure!');
})
.bind('ajax:success', function(event, data, status, xhr) {
alert('success!');
});
});
我在 firebug 控制台中做了等效的操作,当回调在表单上时,它触发了 ajax:success 处理程序。
若要更改窗体上的类,请使用 :form_class 选项将其从 button_to 更改为其他内容
<%= button_to "remote test", remote_test_path, :remote => true, :class => 'remote_button', :form_class => 'remote_button_form' %>
然后使用
jQuery(".remote_button_form").bind ...
http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to
评论