[Suggestion]: Use a shim function for components that use script function (not string)
Question
The current approach that converts a component's script to text before placing it in the document is rather limiting. Wouldn't it be possible to use an approach like this, so that the scope is retained?
Put the function in window and use a shim function in the component instead.
original code:
var myVar = 'John';
editor.BlockManager.add('test-block', {
...
script: function () {
alert('Hi ' + myVar);
console.log('the element', this);
},
...
});
follows my suggestion:
function (as a function not string) detected, let's use a shim:
globalThis['test-block'] = identifierOfTheTestBlockComponent.script
<div id="c764"></div>
<script>
var items = document.querySelectorAll('#c764');
for (var i = 0, len = items.length; i < len; i++) {
(window['test-block'].bind(items[i]))();
}
</script>
originally mentioned in a PR here https://github.com/artf/grapesjs/pull/2479#issuecomment-569628660
Answers (1)
Wouldn't it be possible to use an approach like this, so that the scope is retained?
No, because you're trying to mix the scope of the editor environment with the one which will be deployed to the final user (which has nothing to do with the editor, he is only able to see the final HTML/CSS/JS).
Try to check out this issue: https://github.com/artf/grapesjs/issues/2181
Related Questions and Answers
Continue research with similar issue discussions.
Issue #445
calling a function which is outside the component same as explained in issue #395
I am calling a function which is outside the component same as explained in issue #395 but it is returning a string instead of a function I...
Issue #2831
[BUG] Text components don't behave correctly after creating custom components
Hi artf, After creating custom components, the text component does not behave like before. It removes all the naked nodes after changing so...
Issue #1386
Is there any "Resize event" for components?
I want to read the resize event when an element is triggered for resizing. My current Code looks like this, editor.on("component:resize", f...
Issue #3730
Script tag not rendering in HTML page
I created the component as below. site_1 - is my readymade template and it has CSS and javascript. CSS loads properly with the "content" bu...
Paid Plugins That Match This Issue
Curated by issue keywords and label relevance to help you ship faster.
Loading paid plugin recommendations...
Browse Plugin Categories
Jump directly to plugin category pages on the marketplace.