简体   繁体   中英

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. 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. However, Ember Octane doesn't allow for lifecycle hooks. 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.

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.

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.

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.

You want to create your own modifier using 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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