簡體   English   中英

如何使用Ember.js的動作Helper傳遞參數?

[英]How to pass parameters with the action Helper of Ember.js?

我有一個項目列表:

  <ul>
    {{#each applications}}
      <li>
        <a {{bindAttr href="url"}} 
        {{action "appClicked" on="click"}}>                
           {{name}}
        </a>
      </li>
    {{/each}}
  </ul>

點擊它會調用此模板所屬的視圖方法appClicked 我想將一些信息(例如,應用程序的名稱)傳遞給appClicked方法。 類似於{{action "appClicked(name)" on="click"}}

有可能,怎么樣?

顯然,Ember現在已經發展,並且有能力將參數傳遞給動作:

{{action "functionName" parameter}}

在你的情況下,那將是:

<a {{bindAttr href="url"}} 
   {{action "appClicked" name on='click'}}>                
       {{name}}
   </a>

但是,您可以從模型中傳遞任何屬性(如id)而不是名稱。

有關更多信息,請參見http://emberjs.com/guides/templates/actions/

API表示您可以傳遞多個參數。

HTML和把手:

{{officename}} 
<button {{action "actionTest" "hello" "goodbye" officename}}>See parameters through action in the console</button>

控制器:

actionTest: function(a, b, c){
   console.log(a);
   console.log(b);
   console.log(c);
},

在這個jsbin中看到它的實際效果

我正在考慮更多這方面的內容,因為你可以通過實際視圖訪問更多內容。 但扎克,如果你能解釋一下,如果這不是你想要的東西,你究竟要做什么呢?

 App = Ember.Application.create(); App.peopleController = Ember.ArrayController.create({ content: [ { name: 'Roy', url: '#' }, { name: 'Mike', url: '#' }, { name: 'Lucy', url: '#' } ] }); App.PersonView = Ember.View.extend({ tagName: 'li', content: null, linkClicked: function() { console.log(this.getPath('content.name')); } }); 
 <ul> {{#each App.peopleController}} {{#view App.PersonView contentBinding="this"}} <a {{bindAttr href="content.url"}} {{action "linkClicked" on="click"}}> {{content.name}} </a> {{/view}} {{/each}} </ul> 

從子視圖中,您可以附加數據屬性並在控制器中訪問它們。

例如,在您的視圖中,如果您有:

{{#view Ember.Button target="App.controller" action="publish" data-publish=false}}Unpublish{{/view}}

然后在你的控制器中,

App.controller = Ember.Object.extend({
  publish: function(v){
    var status = v['data-publish'];//your additional information is appended to the view.
  }
}

對Veeb答案的改進,記住你有jQuery事件,所以你可以這樣做:

// template
<ul>
  {{#each applications}}
    <li>
      <a {{bindAttr href="url"}} param="abc" {{action "appClicked" on="click"}}>
         {{name}}
      </a>
    </li>
  {{/each}}
</ul>

// In your js code
appClicked: function (event) {
    var param = $(event.target).attr('param');
    ...
}

您可以嘗試將參數設為<li>或<a>標簽的屬性,然后使用jQuery訪問它。

也許是這樣的

// template
<ul>
  {{#each applications}}
    <li>
      <a {{bindAttr href="url"} param="abc"} 
      {{action "appClicked" on="click"}}>                
         {{name}}
      </a>
    </li>
  {{/each}}
</ul>

// In your js code
appClicked: function (event) {
    // You may have to play around and check which DOM element
    // has the the param attribute. From memory it is the parent.
    var param = this.$().parent().attr('param');
    ...
}

暫無
暫無

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

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