簡體   English   中英

EmberJS觸發來自子組件的父組件的操作

[英]EmberJS trigger action on parent component from child

我正在嘗試創建一個下拉菜單組件。 它包含2個組件 - currency-dropdown (parent)dropdown-item (child) 我能夠渲染組件。 但是,當我單擊dropdown-item組件時,我無法在父組件上觸發操作。

我試圖將選定的組件數據發送到父組件。 我嘗試設置targetObject和我在這里找到的許多其他組合。 我不知道問題是什么。 當我在每個幫助器中呈現子組件時,我確實在父組件中擴展了_yield 一些幫助將非常感激。 這是我到目前為止所得到的。

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>

對於任何有興趣的人,我已經使我的解決方案成為插件

所以我找到了一種方法,但我認為這可能是一個黑客攻擊。 您的問題是,就上下文而言,您的下拉項目不應該有權訪問您的貨幣下拉列表。 通過使用yield ,您將為下拉項目提供與貨幣下拉列表相同的上下文,而不是貨幣下拉列表本身的上下文。 這是一個奇怪的場景,因為你想要兩全其美,但你只能擁有一個或另一個。 因此,您可以執行以下操作,而不是發送操作:

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

這會調用你想要的動作處理程序。 只有兩個警告:

  1. 它將這些組件耦合在一起,使得dropdown-item組件可能無法重復使用。
  2. dropdown-item組件總是調用該操作,而不僅僅是在父組件訂閱它時。

另外,我不知道你的整個用例,但我認為你可能會試圖使這個組件可重用。 我個人根本不會使用yield ,而只是將下拉項的HTML硬編碼到下拉組件類中。 對某些特定於您的應用的內容進行硬編碼會降低您在應用之外的可重用性,但會讓您更輕松地在應用內部工作(這顯然更為重要)。 在使用變通方法之前,您可能需要再次了解如何使用這些組件。 從長遠來看,像這樣的解決方法總會讓我感到困惑。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM