将点击的DOM元素的引用传递给Ember中的操作处理程序 [英] Pass a reference of the clicked DOM element to the action handler in Ember

查看:179
本文介绍了将点击的DOM元素的引用传递给Ember中的操作处理程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组按钮,其状态我想切换一个类活动。如果我有一个按钮,那么我将绑定活动的类到控制器属性,并在点击处理程序中切换该属性:

I have a set of buttons whose state I wish to toggle with a class active. If I had a single button, then I would bind the active class to a controller property and toggle that property in the click handler:

<button {{action 'toggle'}} class="{{active}}">model.title</button>

actions: {
  toggle: function() {
    this.set('active', true);
  }
}

但是我有多个按钮,所以我不确定我可以绑定如果我可以将点击的按钮的引用传递给操作处理程序,那将是有用的,但我不知道该怎么做。

But I have multiple buttons, so I am not sure what I can bind. It would be useful if I could pass a reference to the clicked button to the action handler, but I'm not sure how to do this.

{{#each item in model}}
  <button {{action 'toggle' referenceToButton}}>model.title</button>
{{/each}}

actions: {
  toggle: function(buttonReference) {
    // add `active` class to buttonReference
  }
}

什么是最好的方式来完成这个?

What is the best way to accomplish this?

推荐答案

不是模型项目你想通过什么,而不是按钮?

Isn't the model-item what you want to pass and not the button?

然后,您的切换可以在绑定到你的按钮类

Then your toggle can just set an attribute on the item which you bind to your button class.

{{#each item in model}}
  <button {{bind-attr class="item.isActive:active"}} {{action 'toggle' item}}>model.title</button>
{{/each}}

actions: {
  toggle: function(item) {
    item.set('isActive', true);
  }
}

这篇关于将点击的DOM元素的引用传递给Ember中的操作处理程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆