为每个元素绑定一个动作是一个完美的解决方案,也是在 Ember 中处理它的标准方法:
<ul>
{{#each data key="id" as |item|}}
<li {{action "mouseOverLi" on="mouseEnter"}}>
{{item.description}}
</li>
{{/each}}
</ul>
它还为您提供了能够传递 ember 对象而不是传递 DOM 节点的额外好处。例如:
<ul>
{{#each data key="id" as |item|}}
<li {{action "mouseOverLi" on="mouseEnter" item}}>
{{item.description}}
</li>
{{/each}}
</ul>
然后无论你处理什么:
mouseOverLi: function(item){
item.set("description", "Changed to something different!");
}
我怀疑您的反对意见是我们附加了很多事件处理程序,但这是一个老问题,除非您确实有大量奇怪的列表项,否则不应该成为问题。在这种情况下,您的性能问题首先是您有那么多列表项。
就性能而言,jQuery 实际上并没有对mouseenter 做出反应,它根本不能,因为mouseenter 只在ul 上触发一次,而不是在跨子元素移动时触发。那么https://jsfiddle.net/c8hk6ydn/ 是如何工作的呢?在 jQuery 中,mouseenter 是来自mouseover 的合成事件,请参阅:https://github.com/jquery/jquery/blob/2792845534e36c39dbb9c8369ed96aaefa560081/src/event.js#L779。
所以现在,如果你坚持必须拥有,那么你基本上会像在其他情况下一样使用 jQuery。因为无论如何我们都在做一些非标准的事情:
App.HoverListComponent = Ember.Component.extend({
tagName: "ul",
didInsertElement: function(){
this.$().on("mouseenter", "li", function(){
console.log("Whatever you want to do");
});
}
});
然后在模板中:
{{#hover-list}}
{{#each data key="id" as |item|}}
<li>
{{item.description}}
</li>
{{/each}}
{{/hover-list}}
JSBin: http://emberjs.jsbin.com/xiwoqubumo/5/edit?html,css,js,output 或者你可以尝试更原生的 ember-like 并使用 mouseOver 处理它:
App.HoverListComponent = Ember.Component.extend({
tagName: "ul",
mouseMove: function(e){
// @todo Find the closest 'li' if the LI has
// other elements in it.
// @todo Only fire once per element.
if(e.toElement.tagName !== 'LI'){
return;
}
$(e.toElement).css("color", "red");
}
});
但基本上我的观点是,在做 Ember.js 时使用 Ember.js 的方式,不要像 jQuery 那样做,否则你会得到非常尴尬的代码。