我有一个通过JavaScript渲染的模态表单,该模型被称为book。
# controllers/books_controller.rb
def new
@book = Book.new
end
def create
@book = Book.find(params[:id])
@book.save
end
我使用Coffeescript代替新建和编辑HTML:
# views/new.js.coffee
CustomModal.open "<%= j render('books/modal_form', book: @book) %>"
-
# views/create.js.coffee
<% if @book.valid? %>
CustomModal.hide()
# Other callback scripts for showing alert, etc
<% else %>
# Script for showing errors in the modal
<% end %>
触发模态框的链接:
= link_to "Create Book", new_book_path, remote: true
现在,我面临的问题是这个链接仅在书籍列表页面上使用。所以当创建书籍时,js回调会触发警报并更新列表以反映更改。
现在我必须在另一个没有列表的页面中添加这个按钮,因此我需要一个不同的回调(真正的回调无所谓)。
因此,我必须在create.js.coffee中添加类似以下内容:
# views/create.js.coffee
<% if @book.valid? %>
CustomModal.hide()
# if the list exists
# show alert
# update lists
# else
# do different things
# end
<% else %>
# Script for showing errors in the modal
<% end %>
看起来有点不干净,但其实并没有那么糟糕。问题在于我现在有超过3个条件语句,因为“创建图书”按钮在Web应用程序中被多次使用。
那么,对于这个问题,您有什么设计模式的想法吗?
如果定义了回调函数,则调用回调函数 否则执行默认操作
- michalvalasek