2017-04-22 39 views
0

我試圖使用Ember將組件中的輸入和按鈕組的數據發佈到我的REST API中,但是代碼讓我感到困惑,我還沒有找到一個清楚的例子來說明如何去做。發佈表單數據以從Ember組件中休息api

該網站是一個在守望先鋒的競爭遊戲跟蹤器,所以請在遊戲後輸入排名並在列表中查看。有一個表和API中沒有子項的一個端點。基本上是一個簡單的待辦事項應用程序,但我使用組件來保持一切模塊化。我也想添加編輯和刪除,但這超出了這個問題的範圍。

應用程序/模板/組件/附加game.hbs

<form class="form-inline"> 
    <div class="form-group"> 
    <label class="control-label"> 
     Rank <small>(After match)</small> 
     {{input value=rank type="number" min="4" class="form-control"}} 
    </label> 
    </div> 

    <div class="form-group"> 
    <label class="control-label"> 
     Outcome 
     {{#bs-button-group value=outcome type="radio" onChange=(action (mut outcome)) as |bg|}} 
     {{#bg.button type="default" value='W'}}Win{{/bg.button}} 
     {{#bg.button type="default" value='D'}}Draw{{/bg.button}} 
     {{#bg.button type="default" value='L'}}Loss{{/bg.button}} 
     {{/bs-button-group}} 
    </label> 
    </div> 

    <div class="spacer"></div> 

    <div class="form-group"> 
    <button {{action 'saveGame'}} type="submit" class="btn btn-default btn-primary">Save</button> 
    </div> 
</form> 

應用/組件/附加game.js

import Ember from 'ember'; 

export default Ember.Component.extend({ 
    actions: { 
     saveGame() { 
      const outcome = this.get('model.outcome'); 
      const rank = this.get('model.rank'); 
      console.log(outcome); 
      console.log(rank); 
     } 
    } 

}); 

應用程序/ application.hb

{{nav-bar}} 
<div class="container-fluid"> 
    <div class="row"> 
    <div class="col-md-offset-2 col-sm-8 col-md-8 main"> 
     {{add-game}} 
     <br> 
     {{game-table model=model.games}} 
    </div> 
    </div> 
</div> 

{{outlet}} 

我覺得我在那裏有大部分,我只是缺少一些Ember使用的Data Down,Actions Up方法,但還沒有找到一個清晰的例子來解決這個問題,這與我的代碼很相似。正如你可能會告訴我已將代碼發送到控制檯的代碼一樣,但我不確定將它發送到路由然後發送到服務器的最佳方式。我想我需要使用的模式,但具體代碼

我使用ember-bootstrap的造型和自定義按鈕組組件。

整個項目是Github

回答

0

你可以得到灰燼here的DDAU架構的概述。當您想要將操作發送給父級進行處理時,您必須通知組件要執行的任何事件。在這裏,你的情況,如果你要處理的動作saveGame在父(application),那麼你必須動作傳遞到組件add-game在調用組件如下:

**Application.hbs** 

{{game-table model=model.games saveGameInParent=(action 'saveGameInParent')}} 

其中saveGameInParent是動作出現在應用程序控制器中。在組件中,您需要明確調用此操作以將控件從組件傳遞給父項。

**component/add-game.js** 

import Ember from 'ember'; 

export default Ember.Component.extend({ 
    actions: { 
     saveGame() { 
      // do you really mean to access these props from model?? 
      const outcome = this.get('model.outcome'); 
      const rank = this.get('model.rank'); 
      this.saveGameInParent(outcome, rank); 
     } 
    } 
}); 

最後,在你的應用程序控制器,應該有行動命名,saveGameInParent處理來自組件鼓入的後續行動。

**controllers/application.js** 

actions: { 
    saveGameInParent(outcome, rank) { 
    // post your result to the server using any network library. 
    } 
} 

PS:它看起來像您剛纔提到rankoutcome作爲組件的模板文件的直接組件屬性。但在saveGame操作中,您試圖訪問model中的那些,這是您無法做到的。