Web Components: primers passos
Anem a implementar el que ens explica hdeleon.net en aquest video sobre l'implementació de components web sense utilitzar Frameworks:
Per la meva part ho aplicaré en aquest post però modificant el codi per adaptar-ho a aquest entorn i aprofitant continguts de la meva web, com la galeria.
Aquí podeu veure el resultat
Per ara no incluiré cap explicació del codi i les modificacions que he introduit, pero si el podeu trobar aquí abaix
Codi JavaScript
<primcomponentw-list data-title="Llista de test" data-url="https://jsonplaceholder.typicode.com/users" modePicture="true"></primcomponentw-list> <primcomponentw-list data-title="Llista de test - Imatges" data-urlimgs="https://jsonplaceholder.typicode.com/albums/1/photos" date-field="thumbnailUrl" modePicture="true"></primcomponentw-list> <primcomponentw-list data-title="Llista de test 2" data-urlocal="http://nsuarez.com/_js/users.json" data-field="name"></primcomponentw-list>
JavaScript
class PostBlogMostra extends HTMLElement { constructor() { super(); let shadow = this.attachShadow({mode: 'open'}) // Open per a poder manipular l'element via shadow shadow.innerHTML = 'Testejant l\'eina'; this.divHeader = document.createElement('div'); this.divContent = document.createElement('div'); this.uList = document.createElement('ul'); this.modePicture = false; shadow.appendChild(this.divHeader); shadow.appendChild(this.divContent); } connectedCallback() { this.divHeader.innerHTML = `<strong>${this.getAttribute("data-title")}</strong>`; this.divHeader.appendChild(this.uList); let url = this.getAttribute("data-urlocal"); // data-url let field = this.getAttribute("data-field"); // if(this.getAttribute('modePicture')) { this.modePicture=this.getAttribute("modePicture"); } this.divContent.innerHTML = ''; fetch(url) .then(response=>response.json()) .then(json=>json.forEach(element=>{ if(this.modePicture === "true") { this.divContent.innerHTML += `<img src='${element[field]}'></img> ${this.modePicture}` } else { this.uList.innerHTML += `<li>${element['name']} - ${element[field]}</li>` } })); } } customElements.define('primcomponentw-list', PostBlogMostra);