grapesjs icon indicating copy to clipboard operation
grapesjs copied to clipboard

[Question] Changing component attribute from script

Open francesca-cicileo opened this issue 8 years ago • 2 comments

I am extending the 'text' component by adding a new attribute and a script. When a user types a certain character in the text component, I want the script to change the attribute in the component's model, but I'm not sure how to do that. This is my setup for modifying the text component:

var originalTextComp = domc.getType('text');
domc.addType('text', {
    model: originalTextComp.model.extend({
        defaults: Object.assign({}, originalTextComp.model.prototype.defaults, {
          attributes: {
            customAttribute: false,
          },
          script: function() {
            var customAttribute = '{[ attributes.customAttribute ]}';
            var show = function() {
              if (customAttribute) {
                console.log('show');
              }
            };
            var hide = function() {
              if (customAttribute) {
                console.log('hide');
              }
            };

            var checkEventAndRun = function(e) {
              if (e.which == 219 && !customAttribute) {
                customAttribute = true;
                show();
              } else if (e.which == 221 && customAttribute) {
                hide();
                customAttribute = false;
              }
            };

            this.addEventListener('keyup', checkEventAndRun);
            this.addEventListener('blur', hide);
            this.addEventListener('focus', show);
          },
        }),
    }),
    view: originalTextComp.view
  });

I have two problems: the customAttribute is not being loaded into the script properly, and I don't know how to get the value of the customAttribute in the script to change the value of the custom attribute in the model. I have a listener editor.on('component:update:attributes', model => {}); that does not get called, even when I see 'hide' and 'show' in the console (showing that the customAttribute did get changed in the script). The listener is only called when I first place the component on the canvas (so it is working). Any ideas?

francesca-cicileo avatar May 02 '18 15:05 francesca-cicileo

You can access nested properties like this var customAttribute = '{[ attributes.customAttribute ]}'; inside the script. You should use model's properties:

...
customAttribute: '',
script: function() {
...

and then in your script var customAttribute = '{[ customProp ]}'; One more thing, you can't update the variable inside the script and expect it to propagate that change, the script works in a totally separate context #358

artf avatar May 03 '18 21:05 artf

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.

lock[bot] avatar Sep 17 '19 17:09 lock[bot]