2014-11-22 62 views
3

我試圖創建一個下拉菜單組件。它由兩部分組成 - currency-dropdown (parent)dropdown-item (child)。我能夠渲染組件。但是當我點擊dropdown-item組件時,我無法觸發父組件上的操作。EmberJS觸發對子項父組件的操作

我想將選定的組件數據發送給父組件。我嘗試設置targetObject和我在這裏找到的許多其他組合。我不知道是什麼問題。我確實在父組件中擴展了_yield,因爲我在每個幫助器中渲染子組件。一些幫助將不勝感激。 Here is what I've got so far.

App.CurrencyDropdownComponent = Ember.Component.extend({ 
    actions: { 
     itemSelected: function(item) { 
      console.log(item); 
     } 
    }, 
    _yield: function(content, options) { 
     var get = Ember.get, 
     view = options.data.view, 
     parentView = this._parentView, 
     template = get(this, 'template'); 
     if (template) { 
      view.appendChild(Ember.View, { 
       isVirtual: true, 
       tagName: '', 
       _contextView: parentView, 
       template: template, 
       context: get(view, 'content'), 
       controller: get(parentView, 'controller'), 
       templateData: { keywords: parentView.cloneKeywords() } 
      }); 
     } 
    } 
}); 

App.DropdownItemComponent = Ember.Component.extend({ 
    click: function() { 
     this.sendAction('selectItem', this.origContext); 
    } 
}); 

<script type="text/x-handlebars" id="index"> 
    <header> 
    {{#currency-dropdown currencies=model}} 
     {{#dropdown-item targetObject=view selectItem="itemSelected"}} 
     <span class="cdd-selected-tick">&#10004;</span> 
     <span class="font-13">{{name}}</span> 
     <span class="push-right font-11">{{symbol}}</span> 
     {{/dropdown-item}} 
    {{/currency-dropdown}} 
    </header> 
</script> 

<script type="text/x-handlebars" id="components/currency-dropdown"> 
    <div class="cdd-box"> 
    <input class="cdd-input" type="hidden"/> 
    <div class="cdd-selected-box" {{action "toggleDropDown"}}> 
     <strong>Currency</strong> 
     <span class="uppercase"> {{currencies.0.currencyCode}} </span> 
     {{currencies.0.symbol}} 
     <div class="down-arrow"></div> 
    </div> 
    <ul class="cdd-selection-box" > 
     {{#each item in currencies}} 
     <li>{{yield}}</li> 
     {{/each}} 
    </ul> 
    </div> 
</script> 

For anyone interested I have made my solution an addon.

+0

我得到這個工作正常通過消除所有的產量。但是,它不是真正可重用的。 http://emberjs.jsbin.com/yoheza/1/edit – blessenm 2014-11-22 09:52:06

回答

5

於是我找到了一種方法來做到這一點,但我認爲這可能是一個黑客攻擊的一位。您的問題是,就上下文而言,您的下拉菜單應該無法訪問您的貨幣下拉菜單。通過使用yield,您可以爲下拉菜單選擇與貨幣下拉相同的上下文,而不是貨幣下拉本身的上下文。這是一個奇怪的場景,因爲你需要兩全其美,但你只能擁有一個或另一個。所以,不要發送動作,你可以這樣做:

this.get('parentView').send('itemSelected', this.origContext); 

這將調用你想要的動作處理程序。有兩個注意事項:

  1. 它將這些組件耦合在一起,以便dropdown-item組件可能不可重用。
  2. dropdown-item組件是總是要去調用操作,而不僅僅是當父組件訂閱它時。

另外,我不知道你的整個的使用情況,但我想你可能會試圖使這個組件重用。我個人完全不會使用yield,而只是將下拉菜單項的HTML硬編碼到下拉組件類中。對特定於應用程序的某些內容進行硬編碼會使其在應用程序外部難以重用,但可以更輕鬆地在應用程序內部進行工作(這顯然更重要)。在使用解決方法之前,您可能需要再次查看如何使用這些組件。從長遠來看,像這樣的解決方法總是會回來咬我。

+0

謝謝你的工作。我基本上試圖創建一個下拉組件,我們可以爲選擇項目指定一個模板,如果可能的話,選擇一個項目的模板。您可能是太可重用的。我只是搞清楚組件及其用法。產量有點讓這個東西變得複雜。 – blessenm 2014-11-22 18:22:49