在Ember中渲染一个引导模态内的表单

时间:2013-12-23 16:17:15

标签: ember.js ember-data

在Ember中已经有很多关于模态的问题(如this onethis 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模式。在这个钩子里面,当点击关闭按钮以清除模态插座时,我也会听到bootstrap触发的hidden.bs.modal事件。

App.PersonEditView = Ember.View.extend

  didInsertElement: ->
    @$('.modal').modal('show').on 'hidden.bs.modal', =>
      @get('controller').send('closeModal')

我的问题是,如何在服务器上验证之后定义一个save动作来关闭模式(使用bootstraps动画)?我看到的事件序列是: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

1 个答案:

答案 0 :(得分:1)

尝试将save操作定位到视图:

<button type="button" class="btn btn-primary" {{action "save" target="view"}}>Save</button>

并在控制器中调用save方法。该方法将返回一个承诺,当模型中的save方法结算时,该承诺将解决。

App.PersonEditView = Ember.View.extend
  actions:
    save: ->
      @get('controller').save().then(@closeModal.bind(@))

  closeModal: ->
    @$('.modal').modal('hide')


App.PersonEditController = Ember.ObjectController.extend
    save: ->
      @get('model').save()

这样,控制器抽象出模型保存逻辑,当模型保存时,视图会得到通知,因此它可以按预期运行。

确保在控制器中调用save方法而不是发送操作。 send方法不返回任何内容。

希望它有所帮助!