在 Ember 中向 DOM 动态添加新元素的正确方法是什么?例如工具提示。目前,我立即渲染所有工具提示,但它们是隐藏的,仅在鼠标悬停时显示,无论如何渲染都需要时间。我可以使用 jquery 或普通 JS 在事件上附加元素,它可能会起作用,但这是最有效的方法吗?如果仍然能够使用模板就好了,这样代码就不会太大。
最佳答案
在 Ember 应用程序中直接操作 DOM 是非常禁忌的。您当然希望将其设为 Ember 组件!
在任何页面、路由或组件模板中:
{{#if showTooltip}}
{{tooltip text=someMessage}}
{{/if}}
然后在/pods/components/tooltip/component.js 中
export default Ember.Component.extend({
text: 'hello there! this is a tooltip'
})
最后是组件的模板/pods/component/tooltip/template.hbs
<span class='tooltip-text'>{{text}}</span>
在您的控制上下文中,例如组件或 Controller ,您可能有一个像这样的处理程序:
onMouseOver (event) {
this.set('showTooltip', true)
},
onMouseOut (event) {
this.set('showTooltip', false)
}
这些处理程序可以是组件上的操作或只是 native 事件,根据您想要的任何 DOM 交互事件触发。
如果您将 showTooltip
属性设置为 true
,这将为您提供一个基于模板的工具提示,该提示仅在控制上下文中呈现。它非常接近您在 Ember 应用程序中所要求的功能。
关于javascript - 在 Ember 中添加新元素到 DOM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45951491/