gpt4 book ai didi

ember.js - 在 Ember 中的引导模式内渲染表单

转载 作者:行者123 更新时间:2023-12-02 09:11:52 26 4
gpt4 key购买 nike

已经有很多问题询问 Ember 中的模态(例如 this onethis one )。甚至是cookbook has an article这解释了如何使用模态,但这些都不涵盖需要在模态中从服务器进行验证的表单提交(即,用户名已被采用)。

按照食谱,我的应用程序模板中有一个命名导出。

{{outlet}}
{{outlet modal}}

以及触发在模式导出内渲染模板的操作(使用 Bootstrap )。

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 函数以启用引导模式。在这个钩子(Hook)中,我还监听当单击关闭按钮以清除模式导出时 bootstrap 触发的 hidden.bs.modal 事件。

App.PersonEditView = Ember.View.extend

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

我的问题是,如何定义一个 save 操作,该操作将在服务器上验证后关闭模式(使用引导动画)?我看到需要的事件序列是,1)在 Controller 上触发 save,2)如果成功保存,关闭模式(这需要调用 @$('.modal' ).modal('隐藏') 从 View 中)。

我不确定 Ember 专家会在这里提出什么建议,因为 View 和 Controller 似乎需要非常密切的通信。

谢谢!

<小时/>

编辑

为了回应 edpaez 的评论,我尝试解决 View 中 save 返回的 promise 。例如,在我的模板中

<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

和 Controller

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

我收到以下错误

Uncaught TypeError: Cannot call method 'then' of undefined

最佳答案

尝试将 save 操作定位到 View :

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

并在 Controller 中调用save方法。该方法将返回一个 promise ,该 promise 将在模型中的 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()

这样, Controller 抽象了模型保存逻辑,并且 View 在模型保存时收到通知,因此它可以按预期运行。

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

希望对你有帮助!

关于ember.js - 在 Ember 中的引导模式内渲染表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20747217/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com