2013-12-23 30 views
5

已經有很多問題詢問Ember中的模態(如this onethis one)。即使是解釋如何使用模態的cookbook has an article,但這些都不包含需要模式(即用戶名已被使用)內服務器驗證的提交內容。在Ember中渲染引導模式中的表單

隨着食譜,我有一個在我的應用程序模板命名插座。

{{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函數以啓用引導模式。在這個鉤子裏面,我還會聽到點擊關閉按鈕清除模式插座時由引導啓動的hidden.bs.modal事件。

App.PersonEditView = Ember.View.extend 

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

我的問題是,我怎麼能定義一個save的行動,將關閉模式(使用白手起家動畫)後,它已經在服務器上驗證?我看到的事件順序是:1)save在控制器上被觸發,2)如果成功保存,關閉模式(這將需要從視圖調用​​)。

我不確定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 
+0

您是否考慮過將'save'操作定位到視圖,在控制器中調用'save' **方法**,該方法返回一個promise,解析模型中'save'的解析?控制器會抽象模型保存邏輯,當承諾解決時,視圖會得到通知。 – edpaez

+0

感謝您的評論。看我的編輯。 – Feech

+0

動作處理程序的返回值用於冒泡。另外,您使用的發送方法不會返回任何內容。你必須直接調用這個方法(不要把它放在動作哈希裏面)。在視圖中:'@get('controller')。save()。then ...' – edpaez

回答

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方法不會返回任何內容。

希望它有幫助!

+0

任何想法如何將這種模式功能包裝到一個組件中,以便我可以重新使用它編輯路線?您只能指定要從組件發送的動作(即'{{my-component save =「save」...}}')並在組件中使用'sendAction()'。我無法直接調用控制器上的方法。 – Feech

+0

將'closeModal'包裝在承諾中,並用'sendAction'發送。然後,如果保存成功,您可以解決承諾並隱藏模式。如果'保存'失敗(例如表單驗證),那麼您可以拒絕承諾。請參閱http://stackoverflow.com/a/20810854/306503 –