From 1109132f09d75da9a28b649c7677bb6ce07c40c0 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:41:45 -0500 Subject: initial commit --- .../api/customelementregistry/define/index.html | 239 +++++++++++++++++++++ files/es/web/api/customelementregistry/index.html | 101 +++++++++ 2 files changed, 340 insertions(+) create mode 100644 files/es/web/api/customelementregistry/define/index.html create mode 100644 files/es/web/api/customelementregistry/index.html (limited to 'files/es/web/api/customelementregistry') diff --git a/files/es/web/api/customelementregistry/define/index.html b/files/es/web/api/customelementregistry/define/index.html new file mode 100644 index 0000000000..5ab2ecb1b9 --- /dev/null +++ b/files/es/web/api/customelementregistry/define/index.html @@ -0,0 +1,239 @@ +--- +title: CustomElementRegistry.define() +slug: Web/API/CustomElementRegistry/define +translation_of: Web/API/CustomElementRegistry/define +--- +

{{APIRef("CustomElementRegistry")}}

+ +

El método define() de la interfaz {{domxref("CustomElementRegistry")}} define un nuevo elemento personalizado.

+ +

Se pueden crear dos tipos de elementos personalizados:

+ + + +

Sintaxis

+ +
customElements.define(name, constructor, options);
+
+ +

Parámetros

+ +
+
name
+
Nombre del nuevo elemento personalizado. Fíjate en que los nombres de elementos personalizados deben contener un guión.
+
constructor
+
Constructor para el nuevo elemento personalizado
+
options {{optional_inline}}
+
Objecto que controla cómo se define el elemento. Actualmente solo se permite una opción: +
    +
  • extends: Cadena que especifica el nombre del elemento preconstruido del cual se va a extender. Se usa para crear elementos personalizados preconstruidos.
  • +
+
+
+ +

Valor de retorno

+ +

Void.

+ +

Excepciones

+ + + + + + + + + + + + + + + + + + + + + + +
ExcepciónDescripción
NotSupportedErrorEl {{domxref("CustomElementRegistry")}} ya contiene una entrada con el mismo nombre o el mismo constructor (o se ha definido ya de alguna otra manera), o se ha especificado extends pero el elemento del que se está intentando extender es desconocido.
SyntaxErrorEl nombre proporcionado no es un nombre válido de elemento personalizado.
TypeErrorEl constructor referenciado no es un constructor
+ +
+

Nota: A menudo se obtienen excepciones NotSupportedErrors cuando el método define() está fallando, pero realmente es un problema relacionado con {{domxref("Element.attachShadow()")}}.

+
+ +

Ejemplos

+ +

Elemento personalizado autónomo

+ +

El siguiente código está tomado de nuestro ejemplo popup-info-box-web-component  (verlo en vivo).

+ +
// Crear una clase para el elemento
+class PopUpInfo extends HTMLElement {
+  constructor() {
+    // Siempre lo primero es llamar a super en el constructor
+    super();
+
+    // Crear una shadow root
+    var shadow = this.attachShadow({mode: 'open'});
+
+    // Crear tres elementos span
+    var wrapper = document.createElement('span');
+    wrapper.setAttribute('class','wrapper');
+
+    var icon = document.createElement('span');
+    icon.setAttribute('class','icon');
+    icon.setAttribute('tabindex', 0);
+
+    var info = document.createElement('span');
+    info.setAttribute('class','info');
+
+    // Coger el contenido del atributo text y ponerlo en el span info
+    var text = this.getAttribute('text');
+    info.textContent = text;
+
+    // Coger el contenido del atributo img (si existe) y ponerlo en el span icon
+    var imgUrl;
+    if(this.hasAttribute('img')) {
+      imgUrl = this.getAttribute('img');
+    } else {
+      imgUrl = 'img/default.png';
+    }
+
+    // El span no puede tener directamente una imagen, pero si contener un elemento img
+    var img = document.createElement('img');
+    img.src = imgUrl;
+    icon.appendChild(img);
+
+    // Crear los estilos CSS e incluirlos en el shadow DOM
+    var style = document.createElement('style');
+
+    style.textContent = '.wrapper {' +
+                           'position: relative;' +
+                        '}' +
+
+                         '.info {' +
+                            'font-size: 0.8rem;' +
+                            'width: 200px;' +
+                            'display: inline-block;' +
+                            'border: 1px solid black;' +
+                            'padding: 10px;' +
+                            'background: white;' +
+                            'border-radius: 10px;' +
+                            'opacity: 0;' +
+                            'transition: 0.6s all;' +
+                            'position: absolute;' +
+                            'bottom: 20px;' +
+                            'left: 10px;' +
+                            'z-index: 3;' +
+                          '}' +
+
+                          'img {' +
+                            'width: 1.2rem' +
+                          '}' +
+
+                          '.icon:hover + .info, .icon:focus + .info {' +
+                            'opacity: 1;' +
+                          '}';
+
+    // adjuntar los elementos creados (spans y estilo) al shadow DOM
+    // notese que el span wrapper contiene los spans icon e info
+
+    shadow.appendChild(style);
+    shadow.appendChild(wrapper);
+    wrapper.appendChild(icon);
+    wrapper.appendChild(info);
+  }
+}
+
+// Definir el nuevo elemento
+customElements.define('popup-info', PopUpInfo);
+
+ +
<popup-info img="img/alt.png" text="Su código de validación de tarjeta (CVC) es una característica
+                                    extra de seguridad — consiste en 3 o 4
+                                    numeros en la parte posterior de su tarjeta.">
+ +
+

Nota: Los constructores de elementos personalizados autónomos deben extender {{domxref("HTMLElement")}}.

+
+ +

Elemento personalizado preconstruido

+ +

El siguiente código está tomado de nuestro ejemplo word-count-web-component (verlo en vivo).

+ +
// Crear una clase para el elemento
+class WordCount extends HTMLParagraphElement {
+  constructor() {
+    // Siempre lo primero es llamar a super en el constructor
+    super();
+
+    // contar palabras del padre de este elemento
+    var wcParent = this.parentNode;
+
+    // la función countWords cuenta palabras (aunque estén separadas por más de un espacio)
+    // que existe en el nodo pasado como parámetro.
+    // innerText está definido para objetos HTMLElement, mientras que textContent para todos los objetos Node
+    // el operador || hace que obtengamos al menos uno de los dos
+
+    function countWords(node){
+      var text = node.innerText || node.textContent
+      return text.split(/\s+/g).length;
+    }
+
+    var count = 'Words: ' + countWords(wcParent);
+
+    // // Crear una shadow root
+    var shadow = this.attachShadow({mode: 'open'});
+
+    // Crear un nodo span con el número de palabras
+    var text = document.createElement('span');
+    text.textContent = count;
+
+    // Añadirlo a la shadow root
+    shadow.appendChild(text);
+
+
+    // Actualizar el contador cuando el contenido del elemento cambie
+    setInterval(function() {
+      var count = 'Words: ' + countWords(wcParent);
+      text.textContent = count;
+    }, 200)
+
+  }
+}
+
+// Define the new element
+customElements.define('word-count', WordCount, { extends: 'p' });
+ +
<p is="word-count"></p>
+ +

Especificaciones

+ + + + + + + + + + + + + + +
EspecificaciónEstadoComentario
{{SpecName("HTML WHATWG", "custom-elements.html#dom-customelementregistry-define", "customElements.define()")}}{{Spec2("HTML WHATWG")}}Initial definition.
+ +

Compatibilidad navegadores

+ +
+ + +

{{Compat("api.CustomElementRegistry.define")}}

+
diff --git a/files/es/web/api/customelementregistry/index.html b/files/es/web/api/customelementregistry/index.html new file mode 100644 index 0000000000..624bc8f1fb --- /dev/null +++ b/files/es/web/api/customelementregistry/index.html @@ -0,0 +1,101 @@ +--- +title: CustomElementRegistry +slug: Web/API/CustomElementRegistry +tags: + - API + - CustomElementRegistry + - Experimental + - Interface + - NeedsTranslation + - Reference + - TopicStub + - Web Components + - custom elements +translation_of: Web/API/CustomElementRegistry +--- +
{{DefaultAPISidebar("Web Components")}}
+ +

The CustomElementRegistry interface provides methods for registering custom elements and querying registered elements. To get an instance of it, use the {{domxref("window.customElements")}} property.

+ +

Methods

+ +
+
{{domxref("CustomElementRegistry.define()")}}
+
Defines a new custom element.
+
{{domxref("CustomElementRegistry.get()")}}
+
Returns the constuctor for the named custom element, or {{jsxref("undefined")}} if the custom element is not defined.
+
{{domxref("CustomElementRegistry.upgrade()")}}
+
Upgrades a custom element directly, even before it is connected to its shadow root.
+
{{domxref("CustomElementRegistry.whenDefined()")}}
+
Returns an empty {{jsxref("Promise", "promise")}} that resolves when a custom element becomes defined with the given name. If such a custom element is already defined, the returned promise is immediately fulfilled.
+
+ +

Examples

+ +

The following code is taken from our word-count-web-component example (see it live also). Note how we use the {{domxref("CustomElementRegistry.define()")}} method to define the custom element after creating its class.

+ +
// Create a class for the element
+class WordCount extends HTMLParagraphElement {
+  constructor() {
+    // Always call super first in constructor
+    super();
+
+    // count words in element's parent element
+    var wcParent = this.parentNode;
+
+    function countWords(node){
+      var text = node.innerText || node.textContent
+      return text.split(/\s+/g).length;
+    }
+
+    var count = 'Words: ' + countWords(wcParent);
+
+    // Create a shadow root
+    var shadow = this.attachShadow({mode: 'open'});
+
+    // Create text node and add word count to it
+    var text = document.createElement('span');
+    text.textContent = count;
+
+    // Append it to the shadow root
+    shadow.appendChild(text);
+
+
+    // Update count when element content changes
+    setInterval(function() {
+      var count = 'Words: ' + countWords(wcParent);
+      text.textContent = count;
+    }, 200)
+
+  }
+}
+
+// Define the new element
+customElements.define('word-count', WordCount, { extends: 'p' });
+ +
+

Note: The CustomElementRegistry is available through the {{domxref("Window.customElements")}} property.

+
+ +

Specifications

+ + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "custom-elements.html#customelementregistry", "CustomElementRegistry")}}{{Spec2("HTML WHATWG")}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.CustomElementRegistry")}}

-- cgit v1.2.3-54-g00ecf