繁体   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