Adding new components to existing ones
Hello,
I would like to ask if there's any existing support or API for adding new components to an existing component list (e. g. after fetching or generating them dynamically). I'm talking about something like this:
editor.addComponent({
parent: 'parent_id',
component: '<p>New child component</p>'
})
I've studied the documentation and the closest I got is the addComponents() function. Unfortunately, this function specifies no target where the new component should be placed.
I'm asking this because my intention is to use GrapesJS in a real-time collaborative way and sending the whole HTML representation back and forth after every user action is just too slow.
Best regards, Michal
Hi @baxxos,
Are you trying to do something like this: https://jsfiddle.net/ztqsugaw/3/?
First of all, thanks for the fast reply!
Your example definitely helped me, however, if I understand correctly - I have to recursively iterate through the whole virtual GrapesJS DOM in order to retrieve the component I'm looking for? Is there really no other way of obtaining a component object via its ID? Something such as:
myComponent = editor.getComponent(cid);
I'm sorry if this is something that I've overlooked in the documentation.
Unfortunately I am not aware of a simple way to get a specific component object without recursively iterating through them to find the one you want, but that sounds like a great idea!
You might be able to do something like this to get all components and then filter for the one that you want (this code is not fully tested, but hopefully can get you started in the right direction if you're stuck):
function getAllComponents(component) {
component = component || editor.DomComponents.getWrapper();
var components = component.get("components").models;
component.get("components").forEach(function(component) {
components = components.concat(getAllComponents(component));
});
return components;
};
getAllComponents().filter(function(component) { return component.cid == "someID"; } )[0]
You can rely on the view via model and use a query string to find models
const result = [];
const wrapper = editor.DomComponents.getWrapper();
wrapper.view.$el.find('#query-str').each((el, i, $el) => result.push($el.data('model')))
console.log(result);
Probably we should add find() in Component Model but it's important to know that this method will gonna work only with rendered models (otherwise model.view is undefined)
Thanks for your replies, I think my question has been answered and there's not much else to add. I'm closing this now, however the find() method would be a welcome addition to this awesome framework.
This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.