Issue #513💬 RespondidoAbierto el 13 de noviembre de 2017por krunal039Reacciones 0

Edición de modelo y HTML devuelta

Respuesta rápidapor artf

@krunal039 No es un problema, simplemente es cómo has definido un tipo personalizado. Si defines rasgos en 'div', los conseguirás ahí. Si necesitas actualizar algún componente anidado, siempre puedes acceder a él desde el propio componente '''js const linkModel = model.components().at(0); ... ```

Lee la respuesta completa abajo ↓

Pregunta

Fragmento de códigoTEXT
Tengo el código de abajo para crear un componente personalizado y quiero recuperar html actualizado vía editor.html(), pero si devolvo HTML incorrecto, seguro que me estoy perdiendo algo otra vez.

necesitamos que la siguiente plantilla devuelva [482](https://github.com/artf/grapesjs/issues/482)
Codeplex: [Plantilla](http://codepen.io/kmpdev/full/LORdOM/)

'function createPCBoxComp(comps, defaultModel, defaultView) {

comps.addType('pcBox', {
      Defina el modelo
      model: defaultModel.extend({
        Extender propiedades predeterminadas
        defaults: Object.assign({}, defaultModel.prototype.defaults, {
          Droppable: falso,
          vacío: 0,
          SRC: '',
          hoverText: 'Enlace a la página del currículo',
          título: 'Enlace curricular',
          a_href: 'https://team.global.test/sites/testUni',
          Objetivo: '_blank',

rasgos: [{
              Tipo: 'texto',
              etiqueta: 'Texto de Crucero',
              nombre: 'hoverText',
              Provisional: 'por ejemplo. Enlace a la página del currículo',
              cambioProp: 1,
            },
            {
              Tipo: 'texto',
              etiqueta: 'Título(al final de la imagen)',
              Nombre: 'Título',
              Provisional: 'por ejemplo. Enlace curricular',
              cambioProp: 1,
            }, {
              Tipo: 'texto',
              etiqueta: 'Enlace para abrir',
              Nombre: 'a_href',
              Provisional: 'por ejemplo. https://team.global.test/sites/testUni',
              cambioProp: 1,
            }, {
              tipo: 'select',
              etiqueta: 'Target',
              Nombre: 'Objetivo',
              Opciones: [{
                  valor: '_parent',
                  nombre: 'This Window'
                },
                {
                  valor: '_blank',
                  nombre: 'New Window'
                },
              ],
              cambioProp: 1,
            },
            {
              Tipo: 'texto',
              etiqueta: 'Fuente de la imagen',
              Nombre: 'SRC',
              Provisional: 'por ejemplo. https://team.global.test/sites/LearningDevLib/test%20portal%20deliverables%20%20approved/2.%20Business%20and%20Role%20Specific/7.test%20technology/Assets_pics_graphics/t3.1_test_engineering/test_tools_training.jpg',
              cambioProp: 1,
            },
          ],
        }),

Initialize(O, opt) {
          defaultModel.prototype.initialize.apply(esto, argumentos);
          var attr = this.get('atributos');
          si (attr.title)
            this.set('title', attr.title);
          si (attr.a_href)
            this.set('título', attr.a_href);
          si (atr.objetivo)
            this.set ('título', atr.objetivo);
          if (attr.hoverText)
            this.set('title', attr.hoverText);
          si (attr.src)
            this.set('title', attr.src);
        },

getAttrToHTML(... args) {
          var attr = defaultModel.prototype.getAttrToHTML.apply(this, args);
          var src = this.get('src');
          si (src)
            attr.src = src;
          título var = this.get('título');
          if (título)
            attr.title = título;
          var a_href = this.get('a_href');
          si (a_href)
            attr.a_href = a_href;
          var objetivo = this.get('target');
          si (objetivo)
            atr.objetivo = objetivo;
          var hoverText = this.get('hoverText');
          if (hoverText)
            attr.hoverText = hoverText;
          regresar la atracción;
        }

}, {
        isComponent(el) {
          si ((el.getAttribute & &
              el.getAttribute('data-gjs-type') == 'pcBox') || el.className === 'cust-section') {
            return {
              tipo: 'pcBox'
            };
          }
        }
      }),

Definir la vista
      view: defaultView.extend({

etiquetaNombre: 'a',
        eventos: {
          'dblclick': 'openModal',
          'click': 'initResize',
        },

inicialize(o) {
          defaultView.prototype.initialize.apply(esto, argumentos);
          this.listenTo(this.model, 'change:target', this.updateTarget);
          this.listenTo(this.model, 'change:title', this.updateTitle);
          this.listenTo(this.model, 'change:hoverText', this.updateHoverText);
          this.listenTo(this.model, 'change:a_href', this.updateLink);
          this.listenTo(this.model, 'active', this.openModal);
          this.listenTo(this.model, 'dblclick active', this.openModal);
          this.listenTo(this.model, 'change:src', this.updateSrc);

this.classEmpty = this.ppfx + 'plh-pc-box';
          if (this.config.modal)
            this.modal = this.config.modal;

if (this.config.am)
            this.am = this.config.am;
        },

updateTitle() {
          $(this.el).find('h4').html(this.model.get("título"));
        },
        updateHoverText() {
          $(this.el).find('p.img__description').html(this.model.get("hoverText"));
        },
        updateLink() {
          $(this.el).find('a').attr('href', this.model.get("a_href"));
        },
        updateTarget() {
          $(this.el).find('a').attr('target', this.model.get("target"));
        },
        updateSrc() {
          var src = this.model.get("src");
          $(this.el).find("img.img__img").attr('src', src);
          if (!src)
            $(this.el).find("img.img__img").addClass(this.classVacty);
          si no,
            $(this.el).find("img.img__img").removeClass(this.classVacty);
        },

openModal(e) {
          var em = this.opts.config.em;
          var editor = em ? em.get('Editor'): '';

si (editor) {
            editor.runCommand('open-assets', {
              Objetivo: esto.modelo,
              onSelect() {
                editor. Modal.close();
                editor. AssetManager.setTarget(null);
              }
            });
          }
        },
        disableClick() {
          this.preventDefault();
        },
        render(... args) {
          this.updateAttributes();
          this.updateClasses();
          var tempTemplate = "<div class=img__wrap><img class=img__img src=" + this.model.get("src") + "><p class=img__description>" + this.model.get("hoverText") + "</div><h4>" + this.model.get("título") + "</h4>";
          var plantilla = "<a href=" + this.model.get("a_href") + " target=" + this.model.get("target") + " onclick='event.preventDefault()'>" + tempTemplate + "</a>"

this.el.className = "pcBox";
          this.el.innerHTML = (plantilla);
          devuelvo esto;
        }
      })
    });
  };
` 
Al obtener HTML de editor.html(), obtengo HTML con el atributo añadido en la raíz (div), pero necesito que el atributo individual se aplique en el correcto según la imagen 2
Regresa por debajo de HTML

! [captura](https://user-images.githubusercontent.com/11716808/32724388-01dfb8dc-c869-11e7-8a5d-d428639a144e.PNG)

pero necesito un HTML inferior

! [captura](https://user-images.githubusercontent.com/11716808/32724402-129cc1e2-c869-11e7-96bd-43f286e642a9.PNG)

Respuestas (3)

artf14 de noviembre de 2017

@krunal039 No es un problema, simplemente es cómo has definido un tipo personalizado. Si defines rasgos en 'div', los conseguirás ahí. Si necesitas actualizar algún componente anidado, siempre puedes acceder a él desde el propio componente '''js const linkModel = model.components().at(0); ...

krunal03914 de noviembre de 2017

@artf gracias por responder, ¿puedes indicarme alguna muestra?

lock[bot]18 de septiembre de 2019

Este hilo se ha bloqueado automáticamente porque no ha habido actividad reciente desde que se cerró. Por favor, abre un nuevo problema para bugs relacionados.

Preguntas y respuestas relacionadas

Continúa investigando con debates sobre temas similares.

Plugins de pago que cumplen con este problema

Seleccionado por temas clave y relevancia de etiquetas para ayudarte a enviar más rápido.

Ver todos los plugins

Cargando recomendaciones de plugins de pago...

Opción gratuita

Consulta los plugins de código abierto de GrapesJS en GitHub O haz una búsqueda rápida en nuestro catálogo gratuito.

Explora plugins gratuitos →
Opción premium

Los plugins premium incluyen soporte, actualizaciones regulares y funciones listas para producción — ahorrando días de trabajo de integración.

Explora plugins premium →

Tutoriales relacionados

Guías detalladas sobre el mismo tema.

Todos los tutoriales →

Explorar categorías de plugins

Ve directamente a las páginas de categorías de plugins en el marketplace.