简体   繁体   English

在 Ember Octane 中附加一个 DOM 元素

[英]Appending a DOM element in Ember Octane

I am currently converting some code from older Ember style to Ember Octane, so I'm a bit new to Octane.我目前正在将一些代码从较旧的 Ember 样式转换为 Ember Octane,所以我对 Octane 有点陌生。 At the heart of the problem, I'd like to use this.element.appendChild to append a div when the element is inserted, and then select and append an SVG to the div and modify it from there.问题的核心是,我想在插入元素时使用this.element.appendChild附加一个div ,然后选择并附加一个 SVG 到 div 并从那里修改它。 However, Ember Octane doesn't allow for lifecycle hooks.但是,Ember Octane 不允许生命周期挂钩。 What's the best way to do this?做到这一点的最佳方法是什么?

For some more detail, this component utilizes D3 to render a graph, so it initializes the setup for the graph by creating a div with the id svg and then selects it and appends an SVG to it, and continues to do D3 stuff to it to render a graph.对于更多细节,该组件使用 D3 来渲染图形,因此它通过创建一个带有 id svgdiv来初始化图形的设置,然后选择它并向其附加一个 SVG,并继续对其执行 D3 操作以渲染图形。

I've looked into ember-render-modifiers , but this seems like a bit of a workaround and a copout from refactoring the code, so I was wondering if there was a better way than this.我研究了ember-render-modifiers ,但这似乎是一种解决方法和重构代码的方法,所以我想知道是否有比这更好的方法。

Nevertheless the ember-render-modifiers is the way to go in Octane, because it'll give you access to the element and it will work on insertion.尽管如此, ember-render-modifiers是 Octane 中的方法,因为它可以让您访问元素,并且可以用于插入。

Have a look at their example.看看他们的例子。

{{#if this.shouldShow}}
  <div {{did-insert this.fadeIn}} class="alert">
    {{yield}}
  </div>
{{/if}}
export default Component.extend({
  fadeIn(element) {
    element.classList.add('fade-in');
  }
});

ember-render-modifiers is intended to ease the transition to Octane. ember-render-modifiers旨在简化向 Octane 的过渡。

You want to create your own modifier using ember-modifier您想使用ember-modifier创建自己ember-modifier

/* component.hbs */
<div {{d3-chart this.data this.options}}></div> 
/* app/modifiers/d3-chart.js */
import { modifier } from 'ember-modifier';

export default modifier(element, [data, options] => {
  /*
    The `element` argument is the element the modifier was invoked on
    The second argument is an array of positional params 

    I'm guessing at the params you'd need; not sure what would be an optimal design since that would depend on what you are doing with d3.

    Append the svg, setup d3, etc in here.
  */

  return () =>  {
    /* Cleanup d3 stuff here for when the element with the modifier is torn down */
  };
});

There are also object-oriented styles for modifiers.修饰符也有面向对象的样式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM