我创建了一个助手,用于在我的 Meteor 应用程序(在咖啡脚本中)中显示通用模式。
这是 modal.coffee:
showModal = (modalType, title, body, callback) ->
validModals = [ "Error", "YesNo" ]
if not modalType in validModals
alert "Invalid modal type specified" # @todo - find a better way of handling this error
Session.set "modalType", modalType
Session.set "modalTitle", title or ""
Session.set "modalBody", body or ""
modalCallback = callback or undefined
Session.set "showModal", true
Template.modal.title = () ->
Session.get "modalTitle"
Template.modal.body = () ->
Session.get "modalBody"
Template.modal.response = () ->
switch Session.get "modalType"
when "Error"
[{
css: 'cancel',
message: 'OK'
}]
when "YesNo"
[
{
css: 'cancel',
message: "No"
},
{
css: 'btn-primary',
message: "Yes"
},
]
Template.page.shouldShowModal = () ->
Session.get "showModal"
Template.modal.events {
'click .cancel': ->
Session.set "showModal", false
cb = modalCallback
alert "here " + cb
if cb
cb(false)
'click .btn-primary': ->
Session.set "showModal", false
cb = Session.get "modalCallback"
if cb
cb(true)
}
模板很无聊。
这是我的客户端代码(在这个助手的调用者中):
Template.details.events {
'click .remove': () ->
showModal "YesNo",
"Are you sure you want to delete this item?",
"Deleting an items can't be undone. Are you sure you want to delete?",
(response) =>
if response
Items.remove this._id, (err) =>
if err
showModal "Error", "Error removing item", err.reason
return false;
}
我无法让它执行回调。我看到的所有示例最终都将所有内容都放入了会话中,但显然它无法将函数转换为 json,因此当用户单击确定或取消按钮时,它无法正确反序列化它。
当用户响应我的模式时,我如何执行回调?