{"id":1722,"date":"2024-08-02T11:19:53","date_gmt":"2024-08-02T09:19:53","guid":{"rendered":"https:\/\/blog.sutilweb.eu\/?page_id=1722"},"modified":"2024-08-02T11:19:53","modified_gmt":"2024-08-02T09:19:53","slug":"007-libreria-de-componentes","status":"publish","type":"page","link":"https:\/\/sutilweb.eu\/index.php\/lenguajes\/javascript\/javascript-practico\/19-reactividad\/007-libreria-de-componentes\/","title":{"rendered":"007. Librer\u00eda de Componentes"},"content":{"rendered":"\n<p>Esta secci\u00f3n est\u00e1 siendo el pre\u00e1mbulo para ver como funcionan <strong>librer\u00edas<\/strong> y <strong>frameworks<\/strong> como <a href=\"https:\/\/angular.io\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Angular<\/strong><\/a>, <a href=\"https:\/\/es.react.dev\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>React<\/strong><\/a>, <a href=\"https:\/\/vuejs.org\/\" target=\"_blank\" rel=\"noreferrer noopener\"><strong>Vue<\/strong><\/a>. En el cap\u00edtulo anterior vimos como trabajar un <strong>estado local<\/strong>, donde el <strong>state<\/strong> <strong>global<\/strong> tendr\u00e1 todas las variables que se necesiten para el funcionamiento de la aplicaci\u00f3n, pero que cada <strong>componente de UI<\/strong> puede tener sus propios <strong>estados locales<\/strong>. En el cap\u00edtulo anterior creamos un ejercicio al vuelo, pero lo interesante ser\u00eda crear una librer\u00eda externa y generar tantas <strong>instancias<\/strong> como necesitemos, con lo que tambi\u00e9n trabajar\u00edamos con el principio <strong>DRY<\/strong> (<strong>don\u00b4t repeat yourself<\/strong>).<\/p>\n\n\n\n<!--more-->\n\n\n\n<p>Vamos a crear un archivo denominado <em>05_libreria-componentes-con-estado.html<\/em> y un archivo denominado <em>Component.js<\/em>, que tendr\u00e1n la siguiente sintaxis.<\/p>\n\n\n\n<p>Sintaxis de <em>05_libreria-componentes-con-estado.html<\/em>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">&lt;!DOCTYPE html&gt;\n&lt;html lang=\"es\"&gt;\n&nbsp; &lt;head&gt;\n&nbsp; &nbsp; &lt;meta charset=\"UTF-8\" \/&gt;\n&nbsp; &nbsp; &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" \/&gt;\n&nbsp; &nbsp; &lt;title&gt;Librer\u00eda de componentes con estado&lt;\/title&gt;\n&nbsp; &lt;\/head&gt;\n\n&nbsp; &lt;body&gt;\n&nbsp; &nbsp; &lt;h1&gt;Librer\u00eda de componentes con estado&lt;\/h1&gt;\n\n&nbsp; &nbsp; &lt;form id=\"todo-form\"&gt;\n&nbsp; &nbsp; &nbsp; &lt;input type=\"text\" id=\"todo-item\" placeholder=\"Tarea por hacer\" \/&gt;\n&nbsp; &nbsp; &nbsp; &lt;input type=\"submit\" value=\"Agregar\" \/&gt;\n&nbsp; &nbsp; &lt;\/form&gt;\n\n&nbsp; &nbsp; &lt;h2&gt;Lista de tareas&lt;\/h2&gt;\n\n&nbsp; &nbsp; &lt;ul id=\"todo-list\"&gt;&lt;\/ul&gt;\n\n&nbsp; &nbsp; &lt;script src=\".\/Component.js\"&gt;&lt;\/script&gt;\n&nbsp; &nbsp; &lt;script&gt;\n&nbsp; &nbsp; &nbsp; const d = document;\n\n&nbsp; &nbsp; &nbsp; const app = new Component({\n&nbsp; &nbsp; &nbsp; &nbsp; el: \"#todo-list\",\n&nbsp; &nbsp; &nbsp; &nbsp; data: {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; todoList: [],\n&nbsp; &nbsp; &nbsp; &nbsp; },\n&nbsp; &nbsp; &nbsp; &nbsp; template: function (props) {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (props.todoList.length &lt; 1) {\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return `&lt;p&gt;&lt;em&gt;Lista sin tareas por hacer&lt;\/em&gt;&lt;\/p&gt;`;\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let todos = props.todoList.map((item) =&gt; `&lt;li&gt;${item}&lt;\/li&gt;`).join(\"\");\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return todos;\n&nbsp; &nbsp; &nbsp; &nbsp; },\n&nbsp; &nbsp; &nbsp; });\n\n&nbsp; &nbsp; &nbsp; d.addEventListener(\"DOMContentLoaded\", app.render);\n\n&nbsp; &nbsp; &nbsp; \/\/ Estableciendo valores por defecto al state\n&nbsp; &nbsp; &nbsp; app.setState({\n&nbsp; &nbsp; &nbsp; &nbsp; todoList: [\"Tarea 1\", \"Tarea 2\", \"Tarea 3\"],\n&nbsp; &nbsp; &nbsp; });\n\n&nbsp; &nbsp; &nbsp; d.addEventListener(\"submit\", (e) =&gt; {\n&nbsp; &nbsp; &nbsp; &nbsp; if (!e.target.matches(\"#todo-form\")) return false;\n&nbsp; &nbsp; &nbsp; &nbsp; e.preventDefault();\n&nbsp; &nbsp; &nbsp; &nbsp; const $item = d.getElementById(\"todo-item\");\n&nbsp; &nbsp; &nbsp; &nbsp; if (!$item) return;\n\n&nbsp; &nbsp; &nbsp; &nbsp; \/\/ Actualizar el State de forma reactiva\n&nbsp; &nbsp; &nbsp; &nbsp; const lastState = app.getState();\n&nbsp; &nbsp; &nbsp; &nbsp; lastState.todoList.push($item.value);\n&nbsp; &nbsp; &nbsp; &nbsp; app.setState({\n&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; todoList: lastState.todoList,\n&nbsp; &nbsp; &nbsp; &nbsp; });\n\n&nbsp; &nbsp; &nbsp; &nbsp; \/\/ Limpiar el input\n&nbsp; &nbsp; &nbsp; &nbsp; $item.value = \"\";\n&nbsp; &nbsp; &nbsp; &nbsp; $item.focus();\n&nbsp; &nbsp; &nbsp; });\n&nbsp; &nbsp; &lt;\/script&gt;\n&nbsp; &lt;\/body&gt;\n&lt;\/html&gt;<\/pre>\n\n\n\n<p>Sintaxis de <em>Component.js<\/em>.<\/p>\n\n\n\n<pre class=\"wp-block-preformatted\">const Component = (function () {\n&nbsp; \/\/ Creamos el constructor de este Componente\n&nbsp; const Constructor = function (options) {\n&nbsp; &nbsp; this.el = options.el;\n&nbsp; &nbsp; this.data = options.data;\n&nbsp; &nbsp; this.template = options.template;\n&nbsp; };\n\n&nbsp; \/\/ Agregar los m\u00e9todos al prototipo del constructor del componente\n\n&nbsp; \/\/ Render UI\n&nbsp; Constructor.prototype.render = function () {\n&nbsp; &nbsp; const $el = d.querySelector(this.el);\n&nbsp; &nbsp; if (!$el) return;\n&nbsp; &nbsp; $el.innerHTML = this.template(this.data);\n&nbsp; &nbsp; console.log(this.data);\n&nbsp; };\n\n&nbsp; \/\/ Actualizar el State de forma reactiva\n&nbsp; Constructor.prototype.setState = function (obj) {\n&nbsp; &nbsp; for (let key in obj) {\n&nbsp; &nbsp; &nbsp; if (this.data.hasOwnProperty(key)) {\n&nbsp; &nbsp; &nbsp; &nbsp; this.data[key] = obj[key];\n&nbsp; &nbsp; &nbsp; }\n&nbsp; &nbsp; }\n&nbsp; &nbsp; this.render();\n&nbsp; };\n\n&nbsp; \/\/ Obtenemos una copia inmutable del State\n&nbsp; Constructor.prototype.getState = function () {\n&nbsp; &nbsp; return JSON.parse(JSON.stringify(this.data));\n&nbsp; };\n&nbsp; return Constructor;\n})();<\/pre>\n","protected":false},"excerpt":{"rendered":"<p>Esta secci\u00f3n est\u00e1 siendo el pre\u00e1mbulo para ver como funcionan librer\u00edas y frameworks como Angular, React, Vue. En el cap\u00edtulo [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"parent":1703,"menu_order":6,"comment_status":"closed","ping_status":"closed","template":"","meta":{"_uag_custom_page_level_css":"","site-sidebar-layout":"default","site-content-layout":"","ast-site-content-layout":"default","site-content-style":"default","site-sidebar-style":"default","ast-global-header-display":"","ast-banner-title-visibility":"","ast-main-header-display":"","ast-hfb-above-header-display":"","ast-hfb-below-header-display":"","ast-hfb-mobile-header-display":"","site-post-title":"","ast-breadcrumbs-content":"","ast-featured-img":"","footer-sml-layout":"","ast-disable-related-posts":"","theme-transparent-header-meta":"","adv-header-id-meta":"","stick-header-meta":"","header-above-stick-meta":"","header-main-stick-meta":"","header-below-stick-meta":"","astra-migrate-meta-layouts":"default","ast-page-background-enabled":"default","ast-page-background-meta":{"desktop":{"background-color":"var(--ast-global-color-4)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"ast-content-background-meta":{"desktop":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"tablet":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""},"mobile":{"background-color":"var(--ast-global-color-5)","background-image":"","background-repeat":"repeat","background-position":"center center","background-size":"auto","background-attachment":"scroll","background-type":"","background-media":"","overlay-type":"","overlay-color":"","overlay-opacity":"","overlay-gradient":""}},"footnotes":""},"class_list":["post-1722","page","type-page","status-publish","hentry"],"uagb_featured_image_src":{"full":false,"thumbnail":false,"medium":false,"medium_large":false,"large":false,"1536x1536":false,"2048x2048":false},"uagb_author_info":{"display_name":"Sutil Web","author_link":"https:\/\/sutilweb.eu\/index.php\/author\/sutilweb\/"},"uagb_comment_info":0,"uagb_excerpt":"Esta secci\u00f3n est\u00e1 siendo el pre\u00e1mbulo para ver como funcionan librer\u00edas y frameworks como Angular, React, Vue. En el cap\u00edtulo [&hellip;]","_links":{"self":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1722","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages"}],"about":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/types\/page"}],"author":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/comments?post=1722"}],"version-history":[{"count":1,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1722\/revisions"}],"predecessor-version":[{"id":1723,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1722\/revisions\/1723"}],"up":[{"embeddable":true,"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/pages\/1703"}],"wp:attachment":[{"href":"https:\/\/sutilweb.eu\/index.php\/wp-json\/wp\/v2\/media?parent=1722"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}