【发布时间】:2013-12-23 16:17:14
【问题描述】:
已经有很多关于 Ember 模态的问题(例如 this one 和 this one)。即使cookbook has an article 解释了如何使用模态框,但这些都没有涵盖需要从模态框内的服务器进行验证的表单提交(即,用户名已被使用)。
按照说明书,我的应用程序模板中有一个命名的插座。
{{outlet}}
{{outlet modal}}
以及触发在模态出口内渲染模板的操作(使用引导程序)。
App.ApplicationRoute = Ember.Route.extend
actions:
openModal: (template, model) ->
@controllerFor(template).set('model', model)
@render template, into: 'application', outlet: 'modal'
closeModal: ->
@render '', into: 'application', outlet: 'modal'
显然我是在链接中调用此操作。
<a href="#" {{action openModal "person.edit" model}}>Edit</a>
其中model是当前路由的模型。
在PesonEditView 中,我连接到didInsertElement 函数以启用引导模式。在这个钩子中,我还监听了当单击关闭按钮以清除模态出口时 bootstrap 触发的 hidden.bs.modal 事件。
App.PersonEditView = Ember.View.extend
didInsertElement: ->
@$('.modal').modal('show').on 'hidden.bs.modal', =>
@get('controller').send('closeModal')
我的问题是,我如何定义一个save 操作来关闭模式(使用引导动画) 在服务器上验证后?我看到的事件序列是必需的,1)save 在控制器上被触发,2)如果成功保存,关闭模式(这需要从视图中调用 @$('.modal').modal('hide'))。
我不确定 Ember 专家会在这里提出什么建议,因为看起来视图和控制器似乎需要非常密切地通信。
谢谢!
编辑
针对 edpaez 的评论,我尝试从视图中解决 save 返回的承诺。例如,在我的模板中
<button type="button" class="btn btn-primary" {{action "save" target="view"}}>Save</button>
景色
App.PersonEditView = Ember.View.extend
actions:
save: ->
@get('controller').send('save').then(@closeModal.bind(@))
closeModal: ->
@$('.modal').modal('hide')
# the rest omitted for brevity
还有控制器
App.PersonEditController = Ember.ObjectController.extend
actions:
save: ->
@get('model').save()
我收到以下错误
Uncaught TypeError: Cannot call method 'then' of undefined
【问题讨论】:
-
您是否考虑过将
save操作定位到视图,在控制器中调用save方法,该方法返回一个承诺,当save在模型解决?控制器将抽象模型保存逻辑,并在承诺解决时通知视图。 -
感谢您的评论。查看我的编辑。
-
动作处理程序的返回值用于冒泡。此外,您使用的发送方法不会返回任何内容。您必须直接调用该方法(不要将其放在操作哈希中)。在视图中:
@get('controller').save().then... -
太棒了!非常感谢你的帮助。如果您写了答案,我会将其标记为已接受。
标签: ember.js ember-data