Issue #494Opened November 8, 2017by z-vr0 reactions

Place block as component programmatically

Question

I've created a custom type, and a block

DomComponents.addType('MyComponent', { ... });
BlockManager.add('Component', { content: { type: 'MyComponent' } });

is it possible to insert it into DomComponents by name or any other means? I don't want to be drag'n'dropping the block manually each time. Thanks.

Answers (3)

z-vrNovember 8, 20170 reactions

Oh I found out how to do it -- via editor.addComponents({ type: 'MyComponent' }). Is there a way to insert it into a specific element by a CSS selector?

Found this snippet, but how would i find the correct index?

editor.getComponents().add('<div>Text</div>', {at: index});
z-vrNovember 8, 20170 reactions

ok so what i've done is

export default function iterateChildren(components, fn) {
  components.each((model) => {
    fn(model);
    const childComps = model.get('components');
    iterateChildren(childComps, fn);
  });
}

export function findModels(components, selector) {
  const found = [];
  iterateChildren(components, (model) => {
    const { view } = model;
    if (!view) {
      return;
    }
    const { el } = view;
    const matches = el.matches(selector);
    if (matches) {
      found.push(model);
    }
  });
  return found;
}

and then

const wrapper = DomComponents.getWrapper();
  const models = findModels(wrapper.get('components'), '#hero .text');
  models.forEach((model) => {
    const components = model.get('components');
    components.add({ type: 'ContainerPlugin' }, { at: 0 });
  });

I think traversing the model tree would be a very good feature -- I'll work on the PR at some point. Cheers!

artfNovember 8, 20170 reactions

You can actually get the model from the cash element instance with view.$el.data('model'), so you might make it work with less code

wrapper.view.$el.find('#hero .text').each((el, i, $el) => 
    console.log($el.data('model'))
)

Related Questions and Answers

Continue research with similar issue discussions.

Paid Plugins That Match This Issue

Curated by issue keywords and label relevance to help you ship faster.

View all plugins

Loading paid plugin recommendations...

Browse Plugin Categories

Jump directly to plugin category pages on the marketplace.