<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ivan Torres on Medium]]></title>
        <description><![CDATA[Stories by Ivan Torres on Medium]]></description>
        <link>https://medium.com/@pinguxx?source=rss-67b1440c1d52------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*lQ0q6BxJl6sczX3u.jpeg</url>
            <title>Stories by Ivan Torres on Medium</title>
            <link>https://medium.com/@pinguxx?source=rss-67b1440c1d52------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 04:46:24 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pinguxx/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Easy apps with hyperHTML — 10]]></title>
            <link>https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-10-232bee0ce501?source=rss-67b1440c1d52------2</link>
            <guid isPermaLink="false">https://medium.com/p/232bee0ce501</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[english]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[hyperhtml]]></category>
            <dc:creator><![CDATA[Ivan Torres]]></dc:creator>
            <pubDate>Wed, 10 Apr 2019 16:39:40 GMT</pubDate>
            <atom:updated>2019-04-10T16:39:40.141Z</atom:updated>
            <content:encoded><![CDATA[<h3>Easy apps with hyperHTML — 10</h3><p>3rd party libraries</p><p><a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a></p><ol><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-1-4a56acad9327">Introduction, wire/bind</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-2-1d60fd41bb67">Events and components</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-3-fdc3610fd9e3">Moar about components and simple state management</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-4-31f769e01135">Wire types and custom definitions (intents)</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-5-f6074f373fa6">Custom elements with hyper</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-6-9a3db4278666">Customizing my custom elements</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-7-73d9057e1666">Testing!</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-8-d8a01a5fd1c1">Async loading, placeholder and a Typeahead with hyper</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-9-59ee112be119">Handling routes</a></li><li><strong>3rd party libraries</strong></li></ol><p>Part 10 written by <a href="https://medium.com/u/67b1440c1d52">Ivan Torres</a> and <a href="https://medium.com/u/51448e0bd275">Paul Thompson</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0EgPy4kU90h8ejOLmlC-_Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/C0koz3G1I4I?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Markus Spiske</a> on <a href="https://unsplash.com/search/photos/block?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Combining third-party libraries with your framework can often be challenging. Because hyperHTML is built on JavaScript standards, using it with other libraries is generally pain-free and easy. This is one of the chief beauties of hyper: it plays well with others.</p><p>In part 4 we saw how to define and use intents. In part 2, we worked with components, and in part 5 we looked at custom elements.</p><blockquote>If you missed any of those parts, head back now and review them. We’ll build on what we learned there.</blockquote><p>Today, we are going to use 3rd party libraries to spice up all three of these. Just load ‘n use.</p><h3>Time 📅 and intents 😉</h3><p>To start, we are going to use <a href="https://github.com/iamkun/dayjs">dayjs</a>. Dayjs is a simpler and smaller alternative to <a href="https://momentjs.com/">moment.js</a>. If you’re looking for a datetime library with a smaller footprint, a familiar and logical API, dayjs is a great choice. Back in part 4 we had a date format intent that was printing a date in a specific format. It looked like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07d4c76ecd9fc93f606f28cc2d147f2f/href">https://medium.com/media/07d4c76ecd9fc93f606f28cc2d147f2f/href</a></iframe><p>Now lets update it to use dayjs.</p><pre>import dayjs from &#39;dayjs&#39;;</pre><p>Here’s our first attempt to use the intent:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-3rd-01%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-3rd-01%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/991819854c1be7e9f6e8a3297849c414/href">https://medium.com/media/991819854c1be7e9f6e8a3297849c414/href</a></iframe><p>But we now have the full power of dayjs, so why stop here? We can add formatting options to our intent. Check this out:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-3rd-02%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-3rd-02%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d92955273f53c1e799e51d8e6934ce18/href">https://medium.com/media/d92955273f53c1e799e51d8e6934ce18/href</a></iframe><p>If you were expecting another step or two, prepare to be disappointed! That’s all there is to using dayjs inside your intents.</p><h3>Emojis 😊 and Components ✔️</h3><p>We’ve already covered the basics of including 3rd party libraries. To add some fun to our components, we are going to convert some text strings to emojis using the <a href="https://github.com/joypixels/emojify.js">emojify</a> library. If you’re following along at home, go ahead and import the library into a new file.</p><blockquote>Emojify will detect things like :) and :smile: and convert it to an emoji image. See this <a href="https://www.webfx.com/tools/emoji-cheat-sheet/">cheat sheet</a> for more information on what it can do.</blockquote><p>Let’s start with a simple component using hyper.Component. This component is going to receive some text, and then onclick we are going to use emojify to parse and show emojis. The magic happens in this line</p><pre>emojify.replace(this.text);</pre><p>This component is very simple. We pass in text when we construct the component, and save in two places: this.text is what we will transform, and we’ll keep it around inthis._original so we can revert if we need to.</p><p>That too, was easy! Nothing else to do. The full source code:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-3rd-03%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-3rd-03%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/22c17d7677a86e2ae097af65caeaa961/href">https://medium.com/media/22c17d7677a86e2ae097af65caeaa961/href</a></iframe><h3>Charts 📊 and Custom Elements 🎉</h3><p>Lastly, we are going to create charts with the amazing library <a href="https://gionkunz.github.io/chartist-js/index.html">chartist</a>. Chartist allows us to easily create simple or advanced charts. Just give it data and options, start a new chart of the type you want, and voila! This chart element is not complicated, but it is more involved than the intent and component we made earlier. We’ll just hit the highlights of it here.</p><p>As always, first load the package. For chartist to work, we also need to load some CSS.</p><pre>import &quot;chartist/dist/chartist.css&quot;;<br>import Chartist from &quot;chartist&quot;;</pre><p>The only attribute we are going to observe is the type; everything else will be plain getters and setters. We’ll need a get/set for data and for options. We’ll also include a get/set for both called details to make it easy to update everything in one call.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cd3fa4423421c1d99c73d1221a4e142/href">https://medium.com/media/6cd3fa4423421c1d99c73d1221a4e142/href</a></iframe><p>As you can see, we are calling update on every attribute change. This update function is going to either create a chart, or if we already have one, update it. Variables are created in the created() function and updated in render() .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3898c8a94e218d03ddd8c3daa2fea92e/href">https://medium.com/media/3898c8a94e218d03ddd8c3daa2fea92e/href</a></iframe><p>All we’re doing here is creating and storing a &lt;div&gt; in this._el, and starting a chart instance.</p><p>To use this element, we will have a custom-chart element in the page with the type.</p><pre>&lt;custom-chart type=&quot;Line&quot;&gt;&lt;/custom-chart&gt;<br>&lt;custom-chart type=&quot;Bar&quot;&gt;&lt;/custom-chart&gt;</pre><p>Then we can pass data and options to make it render the actual chart</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcd29aac6f8af09671f6fbe14929b53f/href">https://medium.com/media/dcd29aac6f8af09671f6fbe14929b53f/href</a></iframe><p>Full code for the element and example of usage</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-3rd-04%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-3rd-04%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/62dfeb528e980770fa9c53a86ad47523/href">https://medium.com/media/62dfeb528e980770fa9c53a86ad47523/href</a></iframe><p>What? We’re already done with this part? There’s no crazy hoops to jump through to add 3rd-party libraries to hyperHTML? There’s no magic code dance we have to do? No library-author to ping for an update/change/bugfix? Nope. HyperHTML does a fantastic job of incorporating other libraries. And why would we expect anything different — hyper is standards-based vanilla JavaScript.</p><p>Hopefully we’ve done a good job helping you see the power of combining hyperHTML with some of your favorite libraries. Let us know in the comments what amazing applications you create using hyperHTML+.</p><p>This is the last part of our series on hyperHTML. We will keep writing about hyperHTML in other posts, so let us know if there are topics you want to see covered. We hope you enjoyed this journey as much as we enjoyed writing it. Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=232bee0ce501" width="1" height="1" alt=""><hr><p><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-10-232bee0ce501">Easy apps with hyperHTML — 10</a> was originally published in <a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy apps with hyperHTML — 9]]></title>
            <link>https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-9-59ee112be119?source=rss-67b1440c1d52------2</link>
            <guid isPermaLink="false">https://medium.com/p/59ee112be119</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[english]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[hyperhtml]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ivan Torres]]></dc:creator>
            <pubDate>Thu, 04 Apr 2019 16:03:29 GMT</pubDate>
            <atom:updated>2019-04-10T16:41:38.152Z</atom:updated>
            <content:encoded><![CDATA[<h3>Easy apps with hyperHTML — 9</h3><p>Handling routes</p><p><a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a></p><ol><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-1-4a56acad9327">Introduction, wire/bind</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-2-1d60fd41bb67">Events and components</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-3-fdc3610fd9e3">Moar about components and simple state management</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-4-31f769e01135">Wire types and custom definitions (intents)</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-5-f6074f373fa6">Custom elements with hyper</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-6-9a3db4278666">Customizing my custom elements</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-7-73d9057e1666">Testing!</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-8-d8a01a5fd1c1">Async loading, placeholder and a Typeahead with hyper</a></li><li><strong>Handling routes</strong></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-10-232bee0ce501">3rd party libraries</a></li></ol><p>Part 9 written by <a href="https://medium.com/u/67b1440c1d52">Ivan Torres</a> and <a href="https://medium.com/u/51448e0bd275">Paul Thompson</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*adsYsCwwYGzqLIhnP5AD6Q.jpeg" /></figure><p>If you missed any of the previous parts, now’s a good time to catch up on the ones you missed. Specifically, part 9 builds upon part 8. Recall that we built a table in part 8 and populated it with real data from the cryptocompare api. Now that we are retrieving real data, we can enhance our application even more. This application is a good candidate for routes. By using routes, we can turn it into a single page application or SPA. SPAs don’t need to reload the whole page every time we want to display different parts of the application.</p><p>This is our application so far:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-app-03%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-app-03%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f15f13f45a0056f8efe28585a6d482f/href">https://medium.com/media/6f15f13f45a0056f8efe28585a6d482f/href</a></iframe><p>We are going to add a new tab to display the historical data for the selected coin in the dropdown. To do this, we are going to use state management, our elements, and route management.</p><h3>Reorganization</h3><p>So far we have only used a few elements on the same page. While this is easy to manage, we now need better organization to handle routes and different elements working together.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/205/1*S1ik3vMIJxSjvLrqrKBfjw.png" /></figure><p>We are going to create a folder called elements and move the ones we’ve already created into it. Same with intents. Don’t forget: since we changed the paths we need to update our import statements for all of them.</p><p>Also, let’s create a components folder. We’ll use it soon.</p><p>This is our code now</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-app-04%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-app-04%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2a95b3ef9f65123b404b0b0abf84790/href">https://medium.com/media/d2a95b3ef9f65123b404b0b0abf84790/href</a></iframe><h3>Routing</h3><p>There are a ton of different options for routing and most likely your favorite framework has one… and hyper does as well. And yes it’s YAAT — Yet Another Andrea Tool. <a href="https://github.com/WebReflection/hyperhtml-app">https://github.com/WebReflection/hyperhtml-app</a>. You don’t need to use hyper to use this library, and it is similar to the Express framework in how you define the routes.</p><h4>Route types</h4><ul><li><strong>get(“/path/:param”, cb)</strong>: GET requests to the specified path will be caught. Inside the callback cb, the param will be available as a property on the first argument. e.g: ctx.param</li><li><strong>use(paths, cb)</strong>: Adds middleware to the specified paths. This is similar to get, but it accepts an array of paths</li><li><strong>delete(path, cb)</strong>: Removes a callback from a path</li><li><strong>param(name, cb)</strong>: Allows you to specify a function to use once when a parameter name is passed</li><li><strong>navigate(path)</strong>: Navigate to the path programatically</li></ul><p>For our current project, we are will mostly use get, but as you can see, hyperhtml-app has many options for you to use.</p><p>To get started, let’s import the library and create a couple of routes. Because we’ll be adding an index route, we can get rid of the code inside our index.html and index.js files. We’ll replace it with this:</p><p>New index.html</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0c24046ec58335a6923f698f361da95/href">https://medium.com/media/f0c24046ec58335a6923f698f361da95/href</a></iframe><p>New index.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/103b5b4c2b324ba94d39c7453c613128/href">https://medium.com/media/103b5b4c2b324ba94d39c7453c613128/href</a></iframe><p>When we spin up the server, clicking on the links shows our messages in the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ge9mJJEPMI7N6AJI1Qp00w.png" /></figure><p>Let’s do a quick recap. First, we created an application then we used get (or post or others) to define our paths and a callback. In a real app, the callback will return the view for that path, but for this simple demo, we used it to console.log some text.</p><h4>Components</h4><p>That was pretty easy! But how about we use some components?</p><blockquote>By the way, if you need help with components check out <a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-2-1d60fd41bb67">https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-2-1d60fd41bb67</a>.</blockquote><p>We are going to create a coins.js file that loads a couple of components.</p><p>Let’s start by making two similar components, compare and info. The only difference between them will be that they display something different. Each of these component will be in their own file, Compare.js and Info.js. Take a look at the Compare component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52394903179326b9d3cf985515fe4f37/href">https://medium.com/media/52394903179326b9d3cf985515fe4f37/href</a></iframe><p>Our Info component will be the same, but inside the render() function it will show “Information” and a link to “/”.</p><p>Now coins.js is going to get a bit more complex. First we are going to load both Compare and Info components</p><pre>import Compare from &quot;./compare&quot;;<br>import Info from &quot;./info&quot;;</pre><p>Then in the constructor for the app we are going to create references to our components.</p><pre>constructor(app) {<br>    super();<br>    this.app = app;<br>    this.compare = new Compare();<br>    this.info = new Info();</pre><p>We also going to create a wire to render them.</p><pre>    this.tabc = hyper.wire(this, &quot;:tabcontent&quot;)`&lt;div&gt;`;<br>    this.tabb = hyper.bind(this.tabc);<br>}</pre><p>After adding the default state with coin and path as properties, add an update function that only updates the path for the state. After this we are going to add a renderComponent function that will render the component based on the route</p><pre>renderComponent() {<br>    this.tabb`&lt;div&gt;`; //needed for later<br>    if (this.state.path === &quot;/&quot;) {<br>        this.tabb`${this.compare.update(this.state)}`;<br>    } else {<br>        this.tabb`${this.info.update(this.state)}`;<br>    }<br>    return this.tabc;<br>}</pre><p>And render</p><pre>render() {<br>    return this.html`<br>        &lt;div id=&quot;app&quot; class=&quot;container-fluid&quot;&gt;<br>            ${this.renderComponent()}<br>        &lt;/div&gt;<br>    `;<br>}</pre><p>We also need to update index.js to render coins.js, and index.html to just have the body element. Take a look at the current state of the code:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-app-05%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-app-05%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/677ec62589c2f0abc4b3d2b154e9972a/href">https://medium.com/media/677ec62589c2f0abc4b3d2b154e9972a/href</a></iframe><h3>Layout</h3><p>Now that we have our routes, we need to add the rest of the elements to our page. We’ll make a Search component that holds an input for selecting the coin, and some tabs to change between the views of the table and the coin information.</p><h4>Search</h4><p>For the search we are going to show a “select coin” label along with the input. We won’t start with a coin selected, so at load this is the only thing we are going to show. Let’s take a look at the Search component:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c70b4eadc84de5e7ac106f4a64ca314e/href">https://medium.com/media/c70b4eadc84de5e7ac106f4a64ca314e/href</a></iframe><p>We have to load this new component in coins.js, and bring back our polyfill and elements to index.js</p><p>index.js:</p><pre>import &quot;document-register-element&quot;;<br>import &#39;./intents/intents.js&#39;;<br>import &quot;./elements/Table.js&quot;;<br>import &quot;./elements/Typeahead.js&quot;;</pre><p>coins.js:</p><pre>import Search from &quot;./search&quot;;</pre><p>Then update coins to render search component</p><pre>${Search.for(this, &quot;:search&quot;).update(this.state)}</pre><p>… and that uncovered a bug. Having an empty filter its creating an error in typeahead. Do you think you can find and fix this bug? Take a shot at it, but if you get stuck, see the latest code below</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-app-06%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-app-06%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/6515ea8cf348594b878be1f49c985364/href">https://medium.com/media/6515ea8cf348594b878be1f49c985364/href</a></iframe><h4>Tabs</h4><p>For the Tabs component, we will show a couple of tabs that will serve as our app navigation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12f537b8c545baf49ef9f82224999383/href">https://medium.com/media/12f537b8c545baf49ef9f82224999383/href</a></iframe><p>And in the same way as before, import it and render it in coins.js. Now we can see the two views when clicking on the tabs. Check out the code so far:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-app-07%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-app-07%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/1ec76d701673912c5e641e13e4f45a7a/href">https://medium.com/media/1ec76d701673912c5e641e13e4f45a7a/href</a></iframe><h3>Complete application</h3><p>We are almost there! We need to bring our previous elements back to make them work all together.</p><h4>Compare</h4><p>We have to load the data whenever the user selects a coin from our input. We’ll use the fetch api just like before. We also added a check before render so that we only render the compare table if we have an icon selected.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4530971d72cfa4bcc1be58c8bbfb29a1/href">https://medium.com/media/4530971d72cfa4bcc1be58c8bbfb29a1/href</a></iframe><p>Back in coins.js, we now have to listen for the user selecting a coin from the input. Let’s add an onchange to the base div</p><pre>&lt;div id=&quot;app&quot; onchange=&quot;${this}&quot; class=&quot;container-fluid&quot;&gt;</pre><p>Don’t forget about the event handler itself:</p><pre>onchange(ev) {<br>    this.setState({coin: ev.target.value});<br>}</pre><p>This also uncovers a different bug in the table — columns are not defined when it tries to render. This is a more complex bug, so feel free to check the finished code for the fix.</p><h4>Info</h4><p>The info tab will also fetch the details for the selected coin from cryptocompare, and then show the icon and the name/fullname with a link.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc60d4550fc72e654c985445909c1f16/href">https://medium.com/media/bc60d4550fc72e654c985445909c1f16/href</a></iframe><p>Since we are not showing the tab view until we select something, let’s also hide the tabs themselves by adding the following conditional in render:</p><pre>if (!this.state.coin) {<br>    return;<br>}</pre><p>And done! For an exercise, try to follow how we are passing the properties down to each component with the update() function. To pass data back up, we are listening for the events on the top components :D</p><p>See the complete code and application working:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-app-08%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-app-08%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/43c4eaff407b2f777c2007f924ad91a4/href">https://medium.com/media/43c4eaff407b2f777c2007f924ad91a4/href</a></iframe><p>This post took a while to create, but you know life happens. Hopefully you are still reading and as always, clap away and leave your comments and requests below. We are almost done with the series. We hope you like it so far!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=59ee112be119" width="1" height="1" alt=""><hr><p><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-9-59ee112be119">Easy apps with hyperHTML — 9</a> was originally published in <a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy apps with hyperHTML — 8]]></title>
            <link>https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-8-d8a01a5fd1c1?source=rss-67b1440c1d52------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8a01a5fd1c1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[english]]></category>
            <category><![CDATA[hyperhtml]]></category>
            <dc:creator><![CDATA[Ivan Torres]]></dc:creator>
            <pubDate>Fri, 30 Nov 2018 22:19:26 GMT</pubDate>
            <atom:updated>2019-04-10T16:50:23.115Z</atom:updated>
            <content:encoded><![CDATA[<h3>Easy apps with hyperHTML — 8</h3><p>Async loading</p><p><a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a></p><ol><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-1-4a56acad9327">Introduction, wire/bind</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-2-1d60fd41bb67">Events and components</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-3-fdc3610fd9e3">Moar about components and simple state management</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-4-31f769e01135">Wire types and custom definitions (intents)</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-5-f6074f373fa6">Custom elements with hyper</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-6-9a3db4278666">Customizing my custom elements</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-7-73d9057e1666">Testing!</a></li><li><strong>Async loading, placeholder and a Typeahead with hyper</strong></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-9-59ee112be119">Handling routes</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-10-232bee0ce501">3rd party libraries</a></li></ol><p>Part 8 written by <a href="https://medium.com/u/67b1440c1d52">Ivan Torres</a> and <a href="https://medium.com/u/51448e0bd275">Paul Thompson</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*TnucmAVIXnkD9r43I4JHfQ.jpeg" /></figure><p>There are a few common problems we deal with on a routine basis, when to brush our teeth, whether 3 day old pizza sitting on the counter is still good, and how to show users that something is happening when what is happening can’t be seen. And in a world driven by data, we often want to filter that data to only see what we want. We aren’t going to be able to help you with brushing your teeth or eating habits, but we can do something about the other problems.</p><p>If you’ve been following this tutorial, you already know how powerful hyperHTML combined with custom elements can be. We’ll be able to asynchronously load data while showing placeholder information, and create a typeahead that can filter the date we receive.</p><p>So let’s build a little app that solves these problems. For this part we are going to show a list of top 10 cryptocoins and the conversion to another currency. We will be using the <a href="https://min-api.cryptocompare.com/">cryptocompare</a> api, you can read the documentation <a href="https://min-api.cryptocompare.com/documentation">here</a>. You don’t need to learn the full API if you don’t want, just follow along.</p><p>This is what we are going to build:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*WLVWpg61DmIgZrYFL2NRCQ.png" /></figure><p>Filter on the top right to choose the rate to show.</p><p>Table with the top 10 coins and the rate.</p><p>Button to refresh the top 10.</p><p>Let’s reuse some of our code from <a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-6-9a3db4278666">part 6</a>. Recall in part 6 we made a table with some random data and a few intents. We’ll build upon this table.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-13%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-13%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/dddc9dab1ff1117c039fee06a9dbc07b/href">https://medium.com/media/dddc9dab1ff1117c039fee06a9dbc07b/href</a></iframe><h3>Typeahead</h3><p>Typeaheads are complex elements. For our current project, we’ll use a simplified typeahead. Normally we’d need a lot more code to make this element complete, but for now, a simplified version will work. Whenever the user focuses on the dropdown the list appears, you type and the list filters, click on one of the options and you get the option selected and at that moment we trigger and on change event.</p><p>Be sure to review this code carefully, as we won’t go in depth about it here.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-app-01%3Fctl%3D1%26embed%3D1%26file%3DTypeahead.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-app-01%3Fctl%3D1%26embed%3D1%26file%3DTypeahead.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/397f696ab4d652cd4c73ab154247eaea/href">https://medium.com/media/397f696ab4d652cd4c73ab154247eaea/href</a></iframe><p>Notes on the typeahead code:</p><ul><li>We defined a get/set for options, to allow the user to pass options. We’re using an internal variable to store them. This helps avoid loops if we ever want to set options in our code.</li><li>We’re using Bootstrap classes for styling. dropdown-menu-right will make sure the dropdown of our typeahead is visible on the screen.</li><li>The open() and close() functions will set the state so when we next render, our typeahead will get the proper CSS class to show or hide. Remember, every time we call setState hyperHTML re-renders our element.</li><li>We’re rendering an input that will be inside our element. This is very common thing to do with custom elements — to wrap a native element within our element. By doing this, it’s as if we are extending the native element with additional features.</li><li>We don’t use (<a href="https://viperhtml.js.org/hyperhtml/documentation/#essentials-7">or need!</a>) partial attributes. That’s why we need to wrap the class inside a ${}.</li><li>We map over any options we find and return a wire() for each one. Returning the wire() is important; otherwise, hyperHTML won’t be able to attach the DOM nodes.</li><li>Events let us listen for clicks on the input and open the dropdown, and clicks on the body to close it.</li></ul><p>Before we can use the typeahead, we need to import it in index.js</p><pre>// index.js<br>import &quot;./Typeahead.js&quot;;</pre><pre>const input = document.querySelector(&quot;hyper-input&quot;);</pre><p>And place the custom element in the HTML:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/954e51c557527eef5dadbec3bd9fd7b0/href">https://medium.com/media/954e51c557527eef5dadbec3bd9fd7b0/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ron4PkMQS-Yf-3I8iIERGg.jpeg" /></figure><p>With the basic typeahead out of the way, it’s time to fetch the list of coins. Cryptocompare FTW. We’ll do the fetch here in index.js, and pass parts of the response to our typeahead.</p><pre>const input = document.querySelector(&quot;hyper-input&quot;);</pre><pre>fetch(`https://min-api.cryptocompare.com/data/all/coinlist`)<br>  .then(b =&gt; b.json())<br>  .then(data =&gt; {<br>    input.options = data.Data;<br>  });</pre><p>We should start options with an empty array so we don’t get undefined errors.</p><pre>// typeahead.js<br>created() {<br>    this.options = [];<br>}</pre><p>Now let’s take a look at the table.</p><h3>Table</h3><p>Cryptocompare has an endpoint to get a number of top coins by their total volume across all markets in the last 24 hours. We will use that one to set our table data, so let’s update index.js to do that.</p><pre>fetch(`https://min-api.cryptocompare.com/data/top/totalvol?limit=10&amp;tsym=USD`)<br>   .then(b =&gt; b.json())<br>   .then(data =&gt; {<br>    table.data = data.Data.map(coin =&gt; coin.CoinInfo);<br>   });</pre><p>The table is empty. We need to update the html to target the real attributes</p><pre>&lt;hyper-table coin=&quot;USD&quot;&gt;<br>    &lt;hyper-column label=&quot;ID&quot; attribute=&quot;Id&quot;&gt;&lt;/hyper-column&gt;<br>    &lt;hyper-column label=&quot;Name&quot; attribute=&quot;FullName&quot;&gt;&lt;/hyper-column&gt;<br>    &lt;hyper-column label=&quot;Rate&quot; attribute=&quot;data&quot; sortable=&quot;false&quot;&gt;&lt;/hyper-column&gt;<br>&lt;/hyper-table&gt;</pre><p>We don’t really have a data attribute, but we will see why soon.</p><p>If we reload the page we see the table is empty and then all of a sudden we have the top 10 coins in the table. We should show some loading text so people know things are happening. A good place for this is inside the &lt;tbody&gt; of our table element.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/621a2305a84a11eadcb9665e5a72e872/href">https://medium.com/media/621a2305a84a11eadcb9665e5a72e872/href</a></iframe><p>Now to get the rate, we have to make another call to the server. Just to make it cool we are going to call once for every row in the table. In real production code you probably want to make a call once for everything instead of individual calls.</p><p>We added coin=”USD” to our table above. Since this is a value that can change, let’s put add an observed attribute called coin. When we start the app, it will start the hyper-input with this default value.</p><pre>static get observedAttributes() {<br>    return [&quot;coin&quot;];<br>}</pre><p>In our _renderCell function, let’s check if data is the attribute we are showing and then use the placeholder functionality of hyperHTML. This way we can show some loading text while fetch is loading, and afteward, the rate for the coin.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4be4469db9567e4ca06dbfb25562127a/href">https://medium.com/media/4be4469db9567e4ca06dbfb25562127a/href</a></iframe><p>There’s a lot going on in this code. We’ve primarily encountered wires that look like this:</p><p>return wire()`&lt;div class=${this.state.open}&gt;&lt;/div&gt;`</p><p>However, in the above code, notice that we’re giving the wire a weak map and id: wire(item,` :col${item.Id} `) Hyper will use this to more efficiently use and render the wires. Also, for this wire we are passing an object, instead of HTML. Note that the “any” property is a promise that returns a wire, and the “placeholder” property is a wire. Hyper will use what is in the placeholder property until the promise in any is fulfilled. Whenever fetch is done, we are o return the rate and hyper will remove the placeholder wire and update our element with the new information. Pretty cool!</p><p>Success! We can see our table loading the coins then making 10 more requests to get the rate for each coin.</p><h3>Putting it all Together</h3><p>The next step is to connect the input with the table, we will do that in index.js</p><pre>input.addEventListener(&quot;change&quot;, e =&gt; {<br>    table.coin = input.value;<br>    table.render();<br>});</pre><p>Everytime our input changes, we will update the table coin with the new value and the re-render the table, which will make the rate column make new requests with the new coin and show the new data :D.</p><p>Oh no, we lose the sorting whenever we refresh the data… kind of makes sense since it’s new data. To fix that, let’s move the sorting piece outside our headerclick to its own function, and whenever we add new data we will just re-sort.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdbc0ffb74ba37d322d470ee106bfd35/href">https://medium.com/media/fdbc0ffb74ba37d322d470ee106bfd35/href</a></iframe><p>Alright! Lastly, for our table we will put a last-updated time in the footer. We have a date intent already, but for this we want to show the time also. Making a dateTime intent will help us with that</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3658a51cd1a85726551af9b46eda781/href">https://medium.com/media/c3658a51cd1a85726551af9b46eda781/href</a></iframe><p>Very similar to our previous one but now we are showing the time too.</p><p>In the set data function, we are going to add a date so we have it for the footer</p><pre>set data() {<br>    this._last = Date.now()<br>    ...<br>}</pre><p>And of course the footer now looks like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1db3821e4b32e88254a5dd3f16a03890/href">https://medium.com/media/1db3821e4b32e88254a5dd3f16a03890/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*SA_cH36XcFAoxCW10iXfRw.jpeg" /></figure><p>Code so far</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-app-02%3Fctl%3D1%26embed%3D1%26file%3DTable.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-app-02%3Fctl%3D1%26embed%3D1%26file%3DTable.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/b28d8d49243b21d3daa4b728eb004177/href">https://medium.com/media/b28d8d49243b21d3daa4b728eb004177/href</a></iframe><h3>Refresh</h3><p>Since the top 10 changes rather often, let’s add a refresh button. With this button, the table can be updated without refreshing the whole page.</p><p>First, index.html, under the hyper-table add</p><pre>&lt;p class=&quot;text-center&quot;&gt;&lt;button class=&quot;btn btn-outline-secondary&quot;&gt;Refresh&lt;/button&gt;&lt;/p&gt;</pre><p>Then in index.js, let’s wrap the fetch call for the table in a function called update. This way we can keep calling that every time we click the refresh button. We will also call it when we load the page so that we can get initial data to display.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26f4dc292a99f548c0021264d41580d8/href">https://medium.com/media/26f4dc292a99f548c0021264d41580d8/href</a></iframe><p>And that’s it! Clicking on refresh updates the table and we can see the new timestamp in the footer.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-app-03%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fadvanced-app-03%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f15f13f45a0056f8efe28585a6d482f/href">https://medium.com/media/6f15f13f45a0056f8efe28585a6d482f/href</a></iframe><p>I tried to focus more on the new parts, but if you need a more in-depth explanation of any part let me know in the comments and we can extend that part. Thanks for reading.</p><p>One last O Rly book :D</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/474/1*__l4SOkDgFZFNn6nD2J7xQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8a01a5fd1c1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-8-d8a01a5fd1c1">Easy apps with hyperHTML — 8</a> was originally published in <a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aplicaciones fáciles con hyperHTML — 5]]></title>
            <link>https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-5-402970bf26b4?source=rss-67b1440c1d52------2</link>
            <guid isPermaLink="false">https://medium.com/p/402970bf26b4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[desarrollo-web]]></category>
            <category><![CDATA[hyperhtml]]></category>
            <category><![CDATA[español]]></category>
            <category><![CDATA[tutorial]]></category>
            <dc:creator><![CDATA[Ivan Torres]]></dc:creator>
            <pubDate>Fri, 09 Nov 2018 19:54:20 GMT</pubDate>
            <atom:updated>2018-11-09T19:58:26.322Z</atom:updated>
            <content:encoded><![CDATA[<h3>Aplicaciones fáciles con hyperHTML — 5</h3><p>Custom elements</p><p><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-5-f6074f373fa6">English Version</a></p><p>Parte 5 escrita por <a href="https://medium.com/u/67b1440c1d52">Ivan Torres</a> y <a href="https://medium.com/u/51448e0bd275">Paul Thompson</a>.</p><p>Traducción por <a href="https://medium.com/u/2fc7b2a1d87c">Lupita Hernandez</a> e <a href="https://medium.com/u/67b1440c1d52">Ivan Torres</a>.</p><p><a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a></p><ol><li><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-1-5b887e042c47">Introducción, wire/bind</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-2-dd264fa495e5">Eventos y componentes</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-3-fc4a0503f498">Más acerca de componentes y manejo de estado simple</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-4-785f5d35f895">Tipos de <em>wires</em> y definiciones personalizadas (<em>intents</em>)</a></li><li><strong><em>Custom elements</em> con hyper</strong></li><li>Personalizando mis <em>custom elements</em></li><li>Corriendo pruebas!</li><li>Carga asíncrona, <em>placeholder </em>y un <em>Typeahead</em> con hyper</li><li>Manejando rutas</li><li>Usando librerías externas (<em>3rd party</em>)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*K3i9-YAhQZ7mMwXki57X5g.jpeg" /></figure><h3>Mi propio elemento</h3><p>Si has desarrollado paginas web o aplicaciones por cualquier cantidad de tiempo, lo mas seguro es que has visto componentes personalizados o etiquetas HTML, especialmente si has trabajado con alguno de los nuevos e<em>frameworks</em> de <em>javascript</em>. Cualquiera que sea el nombre, estos componentes usualmente tienen una meta similar: encapsular funciones y lógica en partes de código reutilizables. Después de mucha discusión y desarrollo por parte de la comunidad, finalmente se desarrollaron estas ideas bajo el dosel de <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components">Web Components</a>.</p><blockquote>Web Components constiste en distintas tecnologías independientes. Puedes pensar en Web Components como en widgets de interfaz de usuario reusables que son creados usando tecnología Web abierta. Son parte del navegador, y por lo tanto no necesitan bibliotecas externas como jQuery o Dojo. Un Web Component puede ser usado sin escribir código, simplemente añadiendo una sentencia para importarlo en una página HTML. Web Components usa capacidades estándar, nuevas o aún en desarrollo, del navegador. — MDN</blockquote><p>Para poder lograr esto, la especificación aborda las siguientes tecnologías:</p><ol><li><strong><em>Custom elements</em></strong>: Un<em> set the APIs de javascript</em> que te deja definir la logica de los elementos. Puedes crear funciones como open() y despues puedes llamar esa funcion desde tu element document.querySelector(‘custom-dialog’).open().</li><li><strong><em>Shadow DOM</em></strong>: Te permite usar otros elementos HTML dentro de tu <em>custom element</em>, hasta otros <em>custom elements!</em>. Todo el código dentro de este sera renderizado y estilizado por separado. Esto puede ser un <em>bug</em> o un <em>feature</em>, depende de tu caso de uso.</li><li><strong><em>HTML templates</em></strong>: Dos nuevos elementos &lt;template&gt; y &lt;slot&gt; estas te dejan escribir HTML dentro de tu elemento, pero no son renderizados o mostrados hasta que los actives. &lt;template&gt; y &lt;slot&gt; también pueden ser re-usados después para otras cosas.</li></ol><p>No todas estas tecnologías están lista para usarse en todos los navegadores, y ciertos aspectos son mas difíciles de crear un <em>polyfill</em> que otros, pero estamos acercándonos.</p><p>Por ahora nos vamos a concentrar en <em>custom elements</em>, sin embargo al final te mostraremos como usar <em>shadow DOM</em>. Veremos como hyperHTML puede crear plantillas altamente eficientes. Veremos como podemos hacer todo lo que &lt;template&gt; puede hacer con hyperHTML, excepto el uso nativo de &lt;slot&gt;.</p><h4>&lt;custom-element awesome=”true”&gt;</h4><p>Para empezar a hacer <em>custom elements</em>, necesitamos hacer 3 cosas:</p><ol><li>Un navegador que los soporte, o un <em>polyfill</em>. Recomendamos usar <a href="https://github.com/WebReflection/document-register-element">document-register-element</a>. Este ha sido utilizado en producción durante un tiempo por proyectos como AMP. Alternativamente, Google también tiene uno que puede revisar.</li><li>Una clase que extienda el objetoHTMLElement. Esta clase contendrá toda la lógica de nuestro elemento. También podemos extender de cualquier otro elemento HTML.</li><li>Finalmente, tenemos que “definir” el elemento. Esto es como vamos a registrar nuestro elemento en el navegador, y darle su nombre.</li></ol><p>En el numero 2, mencionamos que hay dos formas de extender la clase de tus elementos, ya sea extendiendo HTMLElement, o extendiendo un elemento predefinido como span. Cuando extendemos HTMLElement nuestro elemento sera “autónomo”. Pero, extender elementos pre-definidos es un poco controversial aun, y aunque la especificación describe la forma de hacerlo, no todos los navegadores lo soportan. Veremos como hacer ambos, pero para nuestro caso de uso del blog, solo extenderemos de HTMLElement.</p><p>Mucho parloteo, muestrame el codigo!!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-01%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-01%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/51d4bf26561358dee56459613d4b9267/href">https://medium.com/media/51d4bf26561358dee56459613d4b9267/href</a></iframe><p>(un pequeño gran detalle, en index.html, como <em>stackblitz</em> esta automagicamente transpilando nuestro código, necesitamos incluir el <em>es5-adapter</em>)</p><p>Vamos a disecar el código un poco:</p><p>Primero nombramos nuestra clase y extendemos HTMLElement. Este sera un elemento autónomo. Después, tenemos una función llamada connectedCallback(), esta sera llamada después de que el navegador haya agregado el elemento al documento. Vamos a platicar mas sobre el ciclo de vida de los elementos mas adelante. Adentro de connectedCallback() estamos solamente añadiendo texto a nuestro elemento.</p><p>En la linea 9 estamos definiendo nuestro elemento. No importa el nombre que escojas, es necesario añadir un guion “-”. En nuestro caso, para usar este elemento vamos a usar la etiqueta &lt;custom-element&gt;&lt;/custom-element&gt;. La función de define también recibe un segundo parámetro que es la clase que describe el elemento.</p><p>Internamente, el navegador mantiene un registro de todos los <em>custom elements</em> que definimos. Una cosa que podemos hacer con el <a href="https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry">CustomElementRegistry</a> es esperar a que los elementos estén definidos. Podemos hacer muchas mas cosas con este, así que revisa la documentación del link anterior.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*Uf6yUZuRXXKeYHFL8jabYg.jpeg" /></figure><p>Y solo para nuestra diversion, vamos a ver como extender un elemento pre-definido:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-02%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-02%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e30ef84d50a0d86f8f597911ab9eb8e/href">https://medium.com/media/3e30ef84d50a0d86f8f597911ab9eb8e/href</a></iframe><h4>Ciclo de vida (<em>Life cycle</em>)</h4><p>Ademas de connectedCallback() hay otras funciones que podemos usar. Veamos que hacen:</p><ul><li><strong>connectedCallback</strong>: llamada cuando el elemento es conectado al documento DOM.</li><li><strong>disconnectedCallback</strong>: llamada cuando el elemento es separado del DOM. Puedes reaccionar a esta acción aquí.</li><li><strong>adoptedCallback</strong>: llamada cuando mueves el elemento a una pagina nueva.</li><li><strong>attributeChangedCallback</strong>: llamada cuando algunos de los atributos que estas monitoreando cambia. Ninguno de los atributos de tu elemento sera monitoreado automáticamente. Para escoger que atributos serán monitoreados puedes agregar esta función:</li></ul><pre>static get observedAttributes() {return [&#39;attr1&#39;, &#39;attr2&#39;]; }</pre><p>Vamos a ver estas funciones en acción:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-03%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-03%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/71e029320471be9409f93c06dc3db2ff/href">https://medium.com/media/71e029320471be9409f93c06dc3db2ff/href</a></iframe><p>Muy bien! Estamos en el camino de tener un nuevo elemento poderoso. Pero que haremos para la plantilla del elemento? Con<em> hyperHTML,</em> podemos renderear cualquier cosa que queramos dentro del elemento y boom!!, <em>custom elements</em> con todo el poder de <em>hyperHTML </em>:D.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*oQV46mV2KLACQJMUNZ6WjA.gif" /></figure><p>Hay que hacer algunos cambios. Primero claro, tenemos que cargar <em>hyperHTML</em>. Después vamos a bind al elemento actual this.html = bind(this);. También vamos a necesitar una función render() la cual sera encargada de renderear la plantilla. Finalmente, necesitamos actualizar nuestro attributeChangedCallback() para que cualquier cambio de atributo también actualizar las propiedades.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-04%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-04%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa906b43387d01b4526dbe89990cf9b9/href">https://medium.com/media/aa906b43387d01b4526dbe89990cf9b9/href</a></iframe><h3>Introduciendo hyperHTML-element</h3><p>Hay mucho mas que aprender acerca de <em>custom elements</em>, pero afortunadamente el maestro <a href="https://medium.com/u/cc83da4b8256">Andrea Giammarchi</a> creo una utilidad que abstrae mucho del API de los <em>custom elements</em> llamada <a href="https://github.com/WebReflection/hyperHTML-element"><em>hyperHTML-element</em></a>.</p><p>Esta es una clase que puedes extender en lugar de HTMLElement, y provee algunas nuevas funciones y propiedades.</p><h4>Funciones</h4><ul><li>Ademas de los observedAttributes también tenemos ahora booleanAttributes. Aqui es donde pondremos los atributos que no requiren un valor. Por ejemplo, &lt;custom-element required&gt;. <em>“required” </em>existe o no así que es un gran candidato para ponerlo como atributo booleano.</li><li>Tanto observedAttributes comobooleanAttributes definen <em>getters</em> y <em>setters</em> por cada atributo observado. Esto significa que no necesitamos hacer this[name] = newValue adentro de attributeChangedCallback.</li><li>created. Esta nueva función sera llamada justo antes de connectedCallback o attributeChangedCallback</li><li>defaultState(). Cada vez que uses this.state, la función defaultState() regresa un objeto que se convierte en, acertaste!, el estado por defecto.</li><li>setState. Actualiza el estado (no necesitas definir defaultState para user setState). Este incluye un pequeño extra: va a llamar render() por ti, asi que tu elemento es actualizado cada vez que cambia el estado.</li><li>render. Esta función debe de regresar el HTML que quieres mostrar en tu elemento.</li><li>Manejadores de eventos (<em>event handlers</em>). En tu plantilla, ahora puedes pasar “<em>this</em>” a el evento que quieras manejar: &lt;div onclick=${this}&gt;&lt;/div&gt;. Si después definimos la función onclick dentro de la clase del elemento, va a ser llamada con el contexto apropiado. También puedes usar data-call para llamar una función diferente: data-call=onAnyEvent onclick=${this}… en este caso la función onAnyEvent sera llamada cuando el usuario haga <em>click</em> en el elemento. Aun mas interesante, los eventos personalizados son muy sencillos de usar: onMyCustomEvent=${this} y defines la función onMyCustomEvent en la clase de tu elemento, listo!.</li><li>define(). Este método estático es para hacer mas sencilla la definición de elementos. En lugar de usar customElements.define usaras MyElement.define(&#39;my-element&#39;)</li><li>Todas las funciones de<em> hyperHTML </em>como bind, component y wire. La única función que no tenemos es define para los <em>intents</em>, dado que la estamos usando para registrar el elemento. Para definir <em>intents</em> vas a usar HyperHTMLElement.intent(…). Vimos estos en la <a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-4-785f5d35f895">parte 4</a> del blog, asegúrate de repasar esta parte si necesitas.</li></ul><p>Los lectores observadores notarán que algunas de estas funciones se utilizan en hiper.Component. Espero que ya estés familiarizado con ellas :D.</p><h4>Propiedades</h4><ul><li>this.html. En nuestro ejemplo anterior usamos this.html = bind(this); en el constructor. Con <em>hyperHTML-element</em> podemos usar this.html directamente.</li><li>state. <em>State </em>es un objecto que contiene el estado del elemento. Esta vació por defecto, o contendrá lo que sea que estas regresando en defaultState, si es que defines esa función.</li><li>Y como lo mencionamos anteriormente, todos los atributos definidos en observedAttributes y booleanAttributes van a tener sus <em>getters</em> y <em>setters</em>, así que al usar this.attr el valor que le des sera reflejado en el atributo. Por ejemplo, &lt;my-element parent=&quot;mama&quot;/&gt;, si haces this.parent te dará el valor de “mama”.</li></ul><p>Muy bien! Vamos a actualizar nuestro elemento previo para usar estas nuevas características:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-05%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-05%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fddcb66cd4af27ffe38bc5f8402148a9/href">https://medium.com/media/fddcb66cd4af27ffe38bc5f8402148a9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*TTLxQoccKUZvMDwsgPJO1A.gif" /></figure><p>Pero, y donde esta <em>shadow DOM</em>?… ah si… es muy fácil:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-06%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-06%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/87d993ac9c16a6c4b898506bdb050024/href">https://medium.com/media/87d993ac9c16a6c4b898506bdb050024/href</a></iframe><p>Revisa la linea 8 this.attachShadow({mode: ‘open’});, si inspeccionas tu elemento con el navegador veras que el <em>shadow DOM</em> esta ahi!.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*Vtc8-XOraDyHOO5Ar741Rg.png" /></figure><p>Hay mucho mas que aprender sobre <em>custom elements</em> y <em>web components</em> en general. En la siguiente parte vamos a escribir algo de lógica en nuestro elemento y actualizar nuestra tabla de la <a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-4-785f5d35f895">parte 4</a> para que sea un <em>custom element</em>. Como siempre, tus comentarios son muy bien recibidos!.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=402970bf26b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-5-402970bf26b4">Aplicaciones fáciles con hyperHTML — 5</a> was originally published in <a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy apps with hyperHTML — 7]]></title>
            <link>https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-7-73d9057e1666?source=rss-67b1440c1d52------2</link>
            <guid isPermaLink="false">https://medium.com/p/73d9057e1666</guid>
            <category><![CDATA[hyperhtml]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[english]]></category>
            <dc:creator><![CDATA[Ivan Torres]]></dc:creator>
            <pubDate>Tue, 16 Oct 2018 18:40:41 GMT</pubDate>
            <atom:updated>2019-04-10T16:50:44.262Z</atom:updated>
            <content:encoded><![CDATA[<h3>Easy apps with hyperHTML — 7</h3><p>Testing</p><p><a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a></p><ol><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-1-4a56acad9327">Introduction, wire/bind</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-2-1d60fd41bb67">Events and components</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-3-fdc3610fd9e3">Moar about components and simple state management</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-4-31f769e01135">Wire types and custom definitions (intents)</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-5-f6074f373fa6">Custom elements with hyper</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-6-9a3db4278666">Customizing my custom elements</a></li><li><strong>Testing!</strong></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-8-d8a01a5fd1c1">Async loading, placeholder and a Typeahead with hyper</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-9-59ee112be119">Handling routes</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-10-232bee0ce501">3rd party libraries</a></li></ol><p>Part 7 written by <a href="https://medium.com/u/67b1440c1d52">Ivan Torres</a>, <a href="https://medium.com/u/51448e0bd275">Paul Thompson</a> and Trevor Ganus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*eH4Rxp5YFEDmzixch010xQ.jpeg" /></figure><p>I’m not a big fan of having 100% code coverage, etc, etc, etc. But if we are writing components, they probably need to be tested as much as possible. We won&#39;t go super deep into testing, but we do want to show a few ways you can test your components and elements.</p><p>A small caveat before we begin: this post isn’t intended to cover everything you need to know about unit testing. Many other tutorials can teach you the basics of how to write code that tests well. Our goal is to show you how to use specific testing tools, with the understanding that you have a basic understanding of unit tests in general. With that out of the way, let’s get started!</p><h3>Enter Tressa</h3><p>Yup, YAAT — Yet Another Andrea Tool. Tressa is a very simple testing utility that we are going to use to test our stuff. It gives us the ability to do synchronized tests and asynchronous tests. It also comes with a basic assert function. Tressa requires consolemd, a module that lets us print using markdown to the console, which is pretty neat. Let’s see an example:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-testing-01%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-testing-01%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b35f829be6196a0ca56f982dcfa96f6/href">https://medium.com/media/6b35f829be6196a0ca56f982dcfa96f6/href</a></iframe><blockquote><strong>Note</strong>: we have to load tressa and consolemd with unpkg because for some reason stackblitz never finds echomd even if installed. Open the real console to see errors, the inner console from stackblitz doesn’t show them for some reason.</blockquote><p>Let&#39;s dissect the code a bit to understand all the pieces</p><ul><li>tressa.title Starts a “section” of tests, by default title adds (“#”) for you</li><li>tressa.end Ends the section of tests and retuns the time spent on them</li><li>tressa and tressa.assert This where you put your assertions with an optional comment as a second argument. You can use either one, there is no difference between them.</li><li>tressa.log console out with markdown, useful to separate parts of your tests</li><li>tressa.async Need to wait for an async operation? Use this wrapper. It returns a promise to test those cases.</li></ul><p>You can see that tressa makes it very easy to test our code. Hopefully, you remember our table created with only hyper.Component. If not, here’s a quick refresh:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-7%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-7%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/246f873eb30b09fb7683a68473a99a56/href">https://medium.com/media/246f873eb30b09fb7683a68473a99a56/href</a></iframe><blockquote>Open the real console to see errors, the inner console from stackblitz doesn’t show them for some reason.</blockquote><h3>Components</h3><p>First let’s load consolemd and tressa. Then, let’s add a test for the footer component in our table. This component doesn’t really do much, so testing should be straightforward. Open the console to see the test results. If you are doing async tests, don’t forget to call the done() callback when your test is finished.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-testing-02%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-testing-02%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/54aed6ebb17f228901e407664057b3ca/href">https://medium.com/media/54aed6ebb17f228901e407664057b3ca/href</a></iframe><p>Cool, let’s move on to the header component. For this one, let’s see if the &lt;thead&gt;is getting icons when we pass the sorted property</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5799074ef28f2c327c0c474eec301674/href">https://medium.com/media/5799074ef28f2c327c0c474eec301674/href</a></iframe><p>Let’s also test the clicking on an &lt;a&gt;tag:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6d7de9b2f4ea57a6225c2d1f64ad1e8/href">https://medium.com/media/f6d7de9b2f4ea57a6225c2d1f64ad1e8/href</a></iframe><p>And now, all the code together:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-testing-03%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-testing-03%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/9719658471802d8528bebd99bf33c37f/href">https://medium.com/media/9719658471802d8528bebd99bf33c37f/href</a></iframe><p>So far, our tests have been on components separated from the DOM. We instantiate the elements with the new keyword. Let’s wrap up the table testing with a test directly on the component already rendered:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-testing-04%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-testing-04%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/29a447ae2817b9870ea25b915fa050c1/href">https://medium.com/media/29a447ae2817b9870ea25b915fa050c1/href</a></iframe><p>We don’t need to write all the tests in this asynchronous way, but I like it since it separates sections of our tests better. Being familiar with the asynchronous tests now will help us later, when we write more complex tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*-DMTBsco27Ad3zJ8209N5Q.png" /></figure><h3>Intents</h3><p>In our component project, we also have a couple of intents — one for icons and one for dates. Let’s test those now. For now, let’s remove the component testing so it’s easier to focus on the intents.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c8feec53641e5fdf538b891bdf27b1fb/href">https://medium.com/media/c8feec53641e5fdf538b891bdf27b1fb/href</a></iframe><p>Well… we found our first bug. If we pass “a”, which is an icon that doesn’t exist in <a href="https://octicons.github.com/">Octicons</a>, we get:</p><p>TypeError: Cannot read property ‘toSVG’ of undefined</p><p>Let’s fix the intent:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad593c51a5c781b6853f8d90031b3977/href">https://medium.com/media/ad593c51a5c781b6853f8d90031b3977/href</a></iframe><p>Sweet, our test passes with the updated code. Now let’s test the date intent:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f780815e279315a3428ae9d96e932a0a/href">https://medium.com/media/f780815e279315a3428ae9d96e932a0a/href</a></iframe><p>Err… that last test shows batman! NaN/NaN/NaN , let’s fix that:</p><p>if (!isNaN(newdate.getTime()) &amp;&amp; typeof newdate.getMonth === ‘function’)</p><p>Yay! Let’s see the result:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-testing-05%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-testing-05%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/14faa172db655aa5c250adfa85573962/href">https://medium.com/media/14faa172db655aa5c250adfa85573962/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*Bs54g93GAySCBSunqJdubg.jpeg" /></figure><h3>Custom elements</h3><p>This is our table as a custom element:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-13%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-13%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/dddc9dab1ff1117c039fee06a9dbc07b/href">https://medium.com/media/dddc9dab1ff1117c039fee06a9dbc07b/href</a></iframe><p>Since we are already using the functions of the table, let’s rewrite those as tests. But first let’s add some utilities and then put all the tests in a single file.</p><p>Let’s see if we are actually loading a table first:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20502d46b07516c25ef1a1babd942933/href">https://medium.com/media/20502d46b07516c25ef1a1babd942933/href</a></iframe><p>It’s there, cool! Notice we get the same result from tressa() as when we were using tressa.assert() in our previous tests. Now let’s test data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58e2a9a20a42a621d3b8fbce4cb4a91f/href">https://medium.com/media/58e2a9a20a42a621d3b8fbce4cb4a91f/href</a></iframe><p>There are a couple of things we want to look at here. First, data will make a row appear, but since it doesn’t have any real data everything will be “-”… except date… lets update the intent to fix that with:</p><p>let formatted = ‘-’,</p><p>Second, data is more real and we see that we have data in our rows and the footer is updated.</p><p>Now let’s test the column functions: add/remove/update</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc012ce6c210df8c87da11055ece23a3/href">https://medium.com/media/fc012ce6c210df8c87da11055ece23a3/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5a4c56cc39ff9023e5ba99e9b2bdf1b/href">https://medium.com/media/d5a4c56cc39ff9023e5ba99e9b2bdf1b/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b1fd1ddc9042753a5ba019891cf5866/href">https://medium.com/media/4b1fd1ddc9042753a5ba019891cf5866/href</a></iframe><p>Last but not least, sorting:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb6c18b201f8905480e5ac33d4f882cb/href">https://medium.com/media/fb6c18b201f8905480e5ac33d4f882cb/href</a></iframe><p>Let’s see everything working together:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-testing-06%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-testing-06%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/933157f75e300fd19796494b9c52caef/href">https://medium.com/media/933157f75e300fd19796494b9c52caef/href</a></iframe><h3>Coverage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*c3fZfe4bPDmWbXpf2rc-MQ.jpeg" /></figure><p>We tested our code, but what if we want to see how much was tested? For this, Istanbul is our friend. We can’t run Istanbul from stackblitz (that I’m aware of), but let’s create a project in github to run it, and that will generate a coverage report.</p><p>For this kind of test we’ll need to have <a href="https://nodejs.org/en/">Node.js</a> and <a href="https://www.npmjs.com/">npm </a>installed. If you’re not familiar with these tools, <a href="https://www.tutorialspoint.com/nodejs/nodejs_npm.htm">here is a great place to start</a>.</p><p>First, we need to change a couple of things. Code-wise we need to remove the tests from index.js and created a file called test.js (clever right?). Then, we need to remove all the imports except intents and table. With those changes, our index.js file looks like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bcb97645f12ab827744a707201f72650/href">https://medium.com/media/bcb97645f12ab827744a707201f72650/href</a></iframe><p>We also will need to setup the test environment, since we are not going to use a browser for our tests. Instead, we are going to use <a href="https://github.com/WebReflection/basicHTML">basicHTML</a>. BasicHTML is a lightweight, dumb, and simple implementation of the HTML standard” — and yes it’s a <a href="#fef8">YAAT</a>.</p><p>So our start of the test file looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce19eb58c44d04146595534f5a67b70c/href">https://medium.com/media/ce19eb58c44d04146595534f5a67b70c/href</a></iframe><p>We bring tressa, then basicHTML, and we set it up. We are also bringing sizzle so we can make complex queries (sizzle is the selector engine used by JQuery so it’s a powerful tool). Then we load hyperHTML, and finally our tests with index.js.</p><p>Then, we setup our fake browser by making it ready and DOMContentLoaded. We can then add our table — just like regular HTML — by using a wire. That’s it! Let’s grab our table and run the same test we wrote previously.</p><p>Now, to run all of this we need a bunch more of dev dependencies. Add this to the package.json file and npm i away</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eaddbfd0b7788a3d3e540b40a8b51a65/href">https://medium.com/media/eaddbfd0b7788a3d3e540b40a8b51a65/href</a></iframe><p>The first part is just our dependencies for the tests. We added a script for running our test — nyc is the istanbul cli. Lastly, we setup nyc so it loads babel to transpile our code, and we add a couple of handy reporters. The HTML reporter will make it so we can look at a pretty web page.</p><p>Since we don’t need the classes to be transpiled lets add a .babelrc to customize the behavior.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cdfdc4f328a7bbd7f5f1e3dbc1329de7/href">https://medium.com/media/cdfdc4f328a7bbd7f5f1e3dbc1329de7/href</a></iframe><p>When testing we use Istanbul and we target firefox 52… why 52?? IDK, sounds like a good number and it was the old ESR :D.</p><p>aaaand then fire up a console terminal, navigate to the folder with your package.json, and enter the command</p><pre>npm test</pre><p>Hopefully you will see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*BF8olzLf8E5Zlb5qH072ig.png" /></figure><p>Open the coverage folder and open index.html to see the report… almost 100%… mm what are we missing? Take a peek at the Table.js file:</p><pre>if (ElOrObj.nodeName === &quot;HYPER-COLUMN&quot;) {</pre><p>Apparently basicHTML is case sensitive. No problem, it’s an easy fix. Let’s do:</p><pre>if (ElOrObj.nodeName &amp;&amp; ElOrObj.nodeName.toLowerCase() === &quot;hyper-column&quot;) {</pre><p>npm test again, open the report… 100%</p><p>Yay! We did it! You can clone the full project here:</p><p><a href="https://github.com/pinguxx/easyapps-7-test1">pinguxx/easyapps-7-test1</a></p><h3>Integration tests</h3><p>For integration testing, I really like <a href="https://www.cypress.io/">cypress</a>. It’s very easy to use and powerful. It lets us create unit, end-to-end, and integration tests. Cypress also gives you the ability to see the state of your web page/app at each stage of the tests.</p><p>With integration testing, we are testing the page directly, so we need to add some things to make that happen. Time does not permit me to explain everything for this, but if you want a more detailed explanation, let me know and I can create a post detailing the process.</p><p>The tl;dr; goes like this:</p><ul><li>Add cypress/rollup/babel and plugins to package.json</li><li>Add test/build scripts in package.json</li><li>run cypress for the first time</li><li>build (babel/bundle) index.js with all the modules used</li><li>start a local server http-server -p 8081</li><li>create a new integration test, table_spec.js is what I called mine</li><li>replicate tressa test and/or add more</li><li>profit!!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kqt4GZ6dpT_aPY3IKNONrw.png" /><figcaption>Test passed :D</figcaption></figure><p>For more information, check out the <a href="https://docs.cypress.io/guides/overview/why-cypress.html#In-a-nutshell">cypress docs</a>. You can also clone and run the tests yourself with this project:</p><p><a href="https://github.com/pinguxx/easyapps-7-test2">pinguxx/easyapps-7-test2</a></p><p>I’m not the best at testing, but this shows a couple of ways to test our components and elements.</p><p>As always, let us know your feedback and what else you want to see in this series. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73d9057e1666" width="1" height="1" alt=""><hr><p><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-7-73d9057e1666">Easy apps with hyperHTML — 7</a> was originally published in <a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aplicaciones fáciles con hyperHTML — 4]]></title>
            <link>https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-4-785f5d35f895?source=rss-67b1440c1d52------2</link>
            <guid isPermaLink="false">https://medium.com/p/785f5d35f895</guid>
            <category><![CDATA[hyperhtml]]></category>
            <category><![CDATA[español]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[desarrollo-web]]></category>
            <dc:creator><![CDATA[Ivan Torres]]></dc:creator>
            <pubDate>Tue, 25 Sep 2018 19:49:33 GMT</pubDate>
            <atom:updated>2018-11-09T20:42:02.264Z</atom:updated>
            <content:encoded><![CDATA[<p>Tipos de <em>wires</em> y definiciones personalizadas (<em>intents</em>)</p><p><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-4-31f769e01135">English Version</a></p><p>Parte 4 escrita por <a href="https://medium.com/u/67b1440c1d52">Ivan Torres</a> y <a href="https://medium.com/u/51448e0bd275">Paul Thompson</a>.</p><p>Traducción por <a href="https://medium.com/u/2fc7b2a1d87c">Lupita Hernandez</a> e <a href="https://medium.com/u/67b1440c1d52">Ivan Torres</a>.</p><p><a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a></p><ol><li><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-1-5b887e042c47">Introducción, wire/bind</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-2-dd264fa495e5">Eventos y componentes</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-3-fc4a0503f498">Más acerca de componentes y manejo de estado simple</a></li><li><strong>Tipos de <em>wires</em> y definiciones personalizadas (<em>intents</em>)</strong></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-5-402970bf26b4"><em>Custom elements</em> con hyper</a></li><li>Personalizando mis <em>custom elements</em></li><li>Corriendo pruebas!</li><li>Carga asíncrona, <em>placeholder </em>y un <em>Typeahead</em> con hyper</li><li>Manejando rutas</li><li>Usando librerías externas (<em>3rd party</em>)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*sN2ihUOzSHet0Wy0I967-w.jpeg" /></figure><p>Anteriormente en este tutorial, vimos como usar componentes con hyperHTML. Construimos una tabla que puede hacer ordenamiento, pero ahora es tiempo de ver algunas de las características adicionales que hyperHTML nos da. Podemos personalizar wire(). Con una función wire() personalizada, podemos transformar nuestras plantillas, o cargar partes de ellas de manera asíncrona. Antes de adentrarnos a esto, vamos a explorar un poco mas la funcionalidad estándar de la función wire() un poco mas.</p><h3>Tipos integrados</h3><p>hyperHTML wire() contiene 2 tipos integrados. El tipo por defecto es “html”, pero tambien soporta svg. Como hemos visto, usar el tipo de “html” no require de trabajo adicional de nuestra parte. Pero, si quieres usar un nodo svg tienes que definirlo explicitamente:</p><p>hyperHTML.wire(data, &#39;svg&#39;)`&lt;rect width=${data.width} height=${data.height} /&gt;`</p><p>El segundo parámetro que pasamos a la función de wire() es el tipo, en este caso svg. Veamos el ejemplo funcionando:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fwire-types-svg%3Fembed%3D1&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fwire-types-svg&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/1becc18075a79296cde21a5801315e50/href">https://medium.com/media/1becc18075a79296cde21a5801315e50/href</a></iframe><p>Recuerdas la <a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-1-5b887e042c47">parte 1</a>. En nuestro ejemplo del reloj, usamos wire() de 2 formas. Primero, lo usamos sin ninguna referencia:</p><p>hyperHTML.wire()`…`</p><p>Pero después también la usamos pasando un objeto a la función:</p><p>hyperHTML.wire(user)`…`</p><p>En aquel primer ejemplo mencionamos que el objeto pasado a <em>wire</em>() no sera actualizado cada vez que sea pintado. Esto es porque al pasarlo a <em>wire</em>() estamos creando una relación entre el y los contenidos del objeto pasado. Esta relación hace mas que optimizar el re-pintado de los elementos, también podemos rehusar este objeto en diferentes lugares con diferentes plantillas. Podemos entonces pasar el mismo objeto pero con diferentes ids:</p><p>hyperHTML.wire(user, &#39;:address&#39;)`…`</p><p>hyperHTML.wire(user, &#39;:profile&#39;)`…`</p><p>hyperHTML.wire(user, &#39;:login&#39;)`…`</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fwire-types-user%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fwire-types-user%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/00070165773afb460cbe459e7a961629/href">https://medium.com/media/00070165773afb460cbe459e7a961629/href</a></iframe><p>También podemos especificar un tipo junto al id:</p><p>hyperHTML.wire(user, &#39;svg:avatar&#39;)</p><h4>Tipos de contenido</h4><p>Tocamos un poco acerca de los diferentes tipos de contenido en la <a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-1-5b887e042c47">parte 1</a>. Vamos a revisarlos a fondo.</p><p>Piensa acerca de las <em>template literals</em>. Dentro de ellas usamos ${…} para evaluar la expresión. Cualquier expression que pases a ${…} sera añadida a tu plantilla dependiendo del tipo. Por ejemplo, hyperHTML es seguro porque la cadena de caracteres pasada sera inyectada comotextContent.</p><p>&lt;p&gt;Hola ${&#39;&lt;script src=&quot;http://badguy.com&quot;&gt;&lt;/script&gt;&#39;}&lt;/p&gt; // whew, safe!</p><p>Pero también puedes forzarlo a ser texto. Para hacer eso, puedes pasar un objeto a hyperHTML:</p><p>&lt;p&gt;Hola ${{text: &#39;Mundo&#39;}}&lt;/p&gt;</p><p>Y si, puedes pasar un nodo y sera agregado:</p><p>&lt;p&gt;Hola ${node}&lt;/p&gt;</p><p>o puedes forzarlo pasando un objeto como arriba, pero con html:</p><p>&lt;p&gt;Hola ${{html: &#39;&lt;strong&gt;Mundo&lt;/strong&gt;&#39;}}&lt;/p&gt;</p><p>Hasta puedes pasar un <em>promise</em>!. Si pasas una promesa (<em>promise</em>), entonces cuando esta sea resuelta sera incluida en la plantilla en cualquiera de los tipos definidos. Para esto tenemos el tipo, <em>any</em>.<em> </em>Este usualmente recibe una promesa, pero puede tomar cualquier otro tipo también, y hyperHTML intentara igualarlo con algun tipo conocido.</p><p>Veamoslos en acción:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fwire-values%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fwire-values%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c3a7455bf97872dc87628b0be023699/href">https://medium.com/media/5c3a7455bf97872dc87628b0be023699/href</a></iframe><p>Pero espera, eso no es todo!. También puedes pasar un arreglo!. Lo único que debes de tener en cuenta al hacerlo es que todos los elementos del arreglo *<strong>tienen</strong>* que ser del mismo tipo: cadena de caracteres o números o nodos, o hasta una lista de promesas. Vas a obtener resultados inesperados si tu arreglo incluye tipos diferentes.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fwire-array%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fwire-array%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/7649214097d7cdbc772a03a3e4bd2315/href">https://medium.com/media/7649214097d7cdbc772a03a3e4bd2315/href</a></iframe><p>Típicamente usamos promesas cuando no tenemos los datos en el momento, pero prometemos tener algo en el futuro. hyperHTML provee <em>placeholder</em> que se muestra mientras los datos se están cargando. Veamos un ejemplo.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fwire-placeholder%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fwire-placeholder%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cc0fd86c285664b7d1b4a69b17428fd/href">https://medium.com/media/1cc0fd86c285664b7d1b4a69b17428fd/href</a></iframe><h4>Atributos</h4><p>Los atributos en los elementos pueden ser atributos regulares, booleanos, o eventos. Si vienes de otro framework, tal vez quieras pensar en usar atributos parciales, pero no los <a href="https://viperhtml.js.org/hyperhtml/documentation/#essentials-7">necesitas</a> (en ingles). Existen otros 2 tipos de atributos de los que necesitamos hablar — <em>style</em> y <em>data</em>. Estos atributos nos ayudaran a construir fácilmente interfaces.</p><p>El atributo de <em>style</em> puede recibir una cadena de caracteres como cualquier otro atributo, o también puedes pasar un objeto:</p><p>wire(ref)`&lt;p style=${{fontSize: 32}}&gt;${&#39;BIG CONTENT&#39;}&lt;/p&gt;`;</p><p>El atributo <em>data</em> te deja pasar un objeto JavaScript al elemento:</p><p>wire(ref)`&lt;p data=${user} /&gt;`;</p><p>El ejemplo como siempre:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fwire-attributes%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fwire-attributes%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd447fc735deb835c41741d46061457e/href">https://medium.com/media/bd447fc735deb835c41741d46061457e/href</a></iframe><h3>Tipos personalizados</h3><p>Podemos usar la funcionalidad de pasar objetos y crear nuestros tipos para mostrar lo que queramos. Dependiendo del nombre sera interpretado como un atributo (si tiene “-” en el nombre) o como un <em>intent </em>personalizado<em>.</em></p><h4>Intent personalizado</h4><p>Para definir un nuevo tipo, vamos a usar hyperHTML.define() . Conveniente no?. La función define() toma 2 parámetros, el nombre y una función de <em>callback.</em></p><p>define(intentName, callback)</p><p>El <em>callback</em> recibe cualquier valor usado en la expresión como parámetro, y regresa datos que serán usados en la plantilla. Esta puede regresar cualquiera de los tipos conocidos.</p><p>Por ejemplo, vamos a definir un <em>intent</em> para mostrar fechas. Cuando recibimos una fecha, vamos a regresar una fecha pero formateada de una forma correcta. Para este ejemplo también usaremos un <em>intent</em> asíncrono.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fwire-custom%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fwire-custom%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/30160cd5aed2e3905a7ba40ec2131c2e/href">https://medium.com/media/30160cd5aed2e3905a7ba40ec2131c2e/href</a></iframe><p>HyperHTML primero intentara igualar a cualquiera de los <em>intents</em> conocidos como <em>html</em>, <em>text</em> o <em>any</em>. Si no puede encontrar uno, seguira ahora buscando en los intentos personalizados registrados, es decir, los que definimos con hyperHTML.define(). Si hyperHTML lo encuentra ahí, entonces usara ese.</p><h4>Atributos personalizados</h4><p>Como mencionamos anteriormente, si defines un <em>intent</em> con “-” en el nombre, sera usado como atributo. Esto significa que podemos agregar cualquier atributo nuevo a cualquier elemento.</p><p>Whoah. En serio?</p><p>Sip, es cierto.</p><p>En el ejemplo siguiente, la función <em>callback</em> va a recibir el <em>element</em> y cualquier otro valor pasado al atributo. Si estas regresando algo, sera usado como valor para este atributo. Nota que para que el atributo personalizado funcione, tienes que usar ${…} para el valor de este.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fwire-custom-attribute%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fwire-custom-attribute%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d4bab8b5b793e13fca78fba9c41c57b/href">https://medium.com/media/0d4bab8b5b793e13fca78fba9c41c57b/href</a></iframe><p>Con lo que sabemos hasta ahora, vamos a actualizar la tabla de la <a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-3-fc4a0503f498">parte 3</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-6%3Fembed%3D1%26file%3DTable.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-6%3Ffile%3DTable.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/f79b57ce40f368da51b588fd1d291c33/href">https://medium.com/media/f79b57ce40f368da51b588fd1d291c33/href</a></iframe><p>Vamos a añadir un icono svg, asi sabremos cual columna esta siendo ordenada y si es ascendente o descendente. También vamos a actualizar nuestros datos para mostrar mejor información sobre el usuario, así como agregar una fecha para poder usar nuestro <em>intent</em> y mostrar las fechas con el formato definido.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-7%3Fembed%3D1%26file%3Dintents.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-7%3Ffile%3Dintents.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/83059b1c4cbf5152707a63db5b981895/href">https://medium.com/media/83059b1c4cbf5152707a63db5b981895/href</a></iframe><p>Estamos usando el paquete de icons <a href="https://octicons.github.com/">Octicons</a>. Ahora veamos el resto del código, revisa con detenimiento los archivos Header y Table.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-7%3Fembed%3D1%26file%3DHeader.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-7%3Ffile%3DHeader.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/a46a87fdd84cb44f9ec0efe85b9ea238/href">https://medium.com/media/a46a87fdd84cb44f9ec0efe85b9ea238/href</a></iframe><p>Grandioso!. Ahora ya sabes que tan poderoso puede ser hyperHTML. Esto es prácticamente todo lo que necesitas saber sobre la librería, pero vamos a empezar a revisar otras utilidades proveídas por <a href="https://medium.com/u/cc83da4b8256">Andrea Giammarchi</a> para agregarlas a nuestro cinturón de herramientas. Con todo esto combinado, vamos a poder crear aplicaciones impresionantes y de alto rendimiento.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=785f5d35f895" width="1" height="1" alt=""><hr><p><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-4-785f5d35f895">Aplicaciones fáciles con hyperHTML — 4</a> was originally published in <a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy apps with hyperHTML — 6]]></title>
            <link>https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-6-9a3db4278666?source=rss-67b1440c1d52------2</link>
            <guid isPermaLink="false">https://medium.com/p/9a3db4278666</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[hyperhtml]]></category>
            <category><![CDATA[english]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ivan Torres]]></dc:creator>
            <pubDate>Sun, 23 Sep 2018 01:22:50 GMT</pubDate>
            <atom:updated>2019-04-10T16:50:58.813Z</atom:updated>
            <content:encoded><![CDATA[<p>Customizing my custom elements</p><p><a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a></p><ol><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-1-4a56acad9327">Introduction, wire/bind</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-2-1d60fd41bb67">Events and components</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-3-fdc3610fd9e3">Moar about components and simple state management</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-4-31f769e01135">Wire types and custom definitions (intents)</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-5-f6074f373fa6">Custom elements with hyper</a></li><li><strong>Customizing my custom elements</strong></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-7-73d9057e1666">Testing!</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-8-d8a01a5fd1c1">Async loading, placeholder and a Typeahead with hyper</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-9-59ee112be119">Handling routes</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-10-232bee0ce501">3rd party libraries</a></li></ol><p>Part 6 written by <a href="https://medium.com/u/67b1440c1d52">Ivan Torres</a>, <a href="https://medium.com/u/51448e0bd275">Paul Thompson</a> and Trevor Ganus.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*Yr8pdpzXyobTf1YLY3PF7w.jpeg" /></figure><h3>Recap</h3><p>In parts 1–5, we talked about the basics of hyperHTML. We also learned about an amazing feature called hyper.Component. We dove into “intents ” that let us extend hyperHTML and simplify our templates. While learning all this we created a simple table:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-7%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-7%3Fctl%3D1%26embed%3D1%26file%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/246f873eb30b09fb7683a68473a99a56/href">https://medium.com/media/246f873eb30b09fb7683a68473a99a56/href</a></iframe><p>Finally, we learned the basics of custom elements and a nice little utility called hyperHTML-Element, which gives us some of the hyper.Component features out of the box, and so much more.</p><p>In part 6, we’re going to discover how we can convert our table from a component to a custom element. We’ll also see how easy it is to add functionality to our custom element, extending it to be even more useful. Using custom elements makes it so easy to reuse our code, a baby could do it — if the <a href="https://www.amazon.com/HTML-Babies-Code-Sterling-Childrens/dp/1454921552">baby knew HTML</a>, and <a href="https://www.amazon.com/Javascript-Babies-Code-Sterling-Childrens/dp/1454921579">JavaScript</a>, of course. Also, once we have a custom element, we don’t need hyperHTML anywhere else in our app unless we want it. This makes the custom elements plug-and-play with any framework. When was the last time a React component could say that?</p><h3>Columns</h3><p>Let’s start thinking about the elements of the table: header, footer and body. For our case, header and footer are the important parts. We will generate the footer based on the data just like before.</p><p>Let’s start with a custom element for the columns. This element will contain the information necessary to render:</p><p>· the label (for the header)</p><p>· the attribute used for this column (from the data)</p><p>· if it’s sortable or not</p><p>· the type of data to display</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-07%3Fctl%3D1%26embed%3D1%26file%3DColumn.js%26view%3Deditor&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-07%3Fctl%3D1%26embed%3D1%26file%3DColumn.js%26view%3Deditor&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bb653bacf9795b4cfbdf9f51e548a98/href">https://medium.com/media/0bb653bacf9795b4cfbdf9f51e548a98/href</a></iframe><p>Simple right? We don’t even render anything, all the heavy lifting will be in the table itself.</p><h3>Table</h3><p>Now let’s generate a custom element with a simple table.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-08%3Fctl%3D1%26embed%3D1%26file%3Dindex.html&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-08%3Fctl%3D1%26embed%3D1%26file%3Dindex.html&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/e53b9b3446cd4897ba55e085428f1b5a/href">https://medium.com/media/e53b9b3446cd4897ba55e085428f1b5a/href</a></iframe><p>Let’s first add a hyper-column to our HTML</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5934656ddb8d5d9261de9b19cb32bd3d/href">https://medium.com/media/5934656ddb8d5d9261de9b19cb32bd3d/href</a></iframe><p>Then, we need to update our created function to read the columns and store them in an array that we can reuse later:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/44192cd507404bf65f992e3887cfe290/href">https://medium.com/media/44192cd507404bf65f992e3887cfe290/href</a></iframe><p>(used [].slice.call instead of […this.querySelectorAll(“hyper-column”)] because of an error using stackblitz)</p><p>And lastly, let’s update our template to use the columns.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d80b914badb93ea13342bc9920a7d36/href">https://medium.com/media/5d80b914badb93ea13342bc9920a7d36/href</a></iframe><p>Well cool. But we are not really using data from anywhere… let’s fix that. We’ll add a data property.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8bd315335fe1a0303ee9f23d356f7c04/href">https://medium.com/media/8bd315335fe1a0303ee9f23d356f7c04/href</a></iframe><p>We now need to update our &lt;tbody&gt; part of the template to show one row for each item in the data.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/af6e2be306a182db3d4249421b7c9348/href">https://medium.com/media/af6e2be306a182db3d4249421b7c9348/href</a></iframe><p>(if wire(column, `col${item.id}`) looks unfamiliar to you, review <a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-4-31f769e01135">part 4</a>!)</p><p>Of course, we still need to pass data to the table. The index file is where we’ll do that.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f98f5bc2fdd4248d72bcfdf2ca17efb2/href">https://medium.com/media/f98f5bc2fdd4248d72bcfdf2ca17efb2/href</a></iframe><p>Let’s see our full code so far:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-09%3Fctl%3D1%26embed%3D1%26file%3DTable.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-09%3Fctl%3D1%26embed%3D1%26file%3DTable.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/18b3af0bb15606a89415a3f2caf8e695/href">https://medium.com/media/18b3af0bb15606a89415a3f2caf8e695/href</a></iframe><p>To finish off the table, we need to add the rest of the columns. Notice, this is very similar to what we’ve done in previous parts of this tutorial!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90a9790ba54772abf9ef40d65dd93eee/href">https://medium.com/media/90a9790ba54772abf9ef40d65dd93eee/href</a></iframe><h3>Intents</h3><p>Recall intents from <a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-4-31f769e01135">part 4</a>? Let’s use intents to display icons and dates correctly. We happen to like the <a href="https://octicons.github.com/">octicon</a> library of icons, but you can feel free to bring your own icon set.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c91c5e5244215098cc4f3ef584563e01/href">https://medium.com/media/c91c5e5244215098cc4f3ef584563e01/href</a></iframe><p>Then extract the rendering of the &lt;td&gt;’s and &lt;th&gt;’s for easier reading.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f0c0a1d81a77f631fd2af3658d71b170/href">https://medium.com/media/f0c0a1d81a77f631fd2af3658d71b170/href</a></iframe><p>(Note that, for user-provided values, you should be sure to use the ‘text’ type. Otherwise, use of ‘html’ could lead to potential HTML injection issues. Normally, hyperHTML will escape HTML used in expressions ${...}).</p><p>We are using state so let’s make sure we have a defaultState set:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a87a3e585a5dca14b70a3e7e5af871a/href">https://medium.com/media/0a87a3e585a5dca14b70a3e7e5af871a/href</a></iframe><p>And again update our template</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13c7c29f82cf71f094771bf8fed297f8/href">https://medium.com/media/13c7c29f82cf71f094771bf8fed297f8/href</a></iframe><p>Much easier to follow :D.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-10%3Fctl%3D1%26embed%3D1%26file%3DTable.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-10%3Fctl%3D1%26embed%3D1%26file%3DTable.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/67ca7295d3630a7b61bf165b069e3117/href">https://medium.com/media/67ca7295d3630a7b61bf165b069e3117/href</a></iframe><h3>State &amp; Events</h3><p>We need to be able to sort the data when a user clicks on the table header. Let’s add onclick=&quot;${this}&quot; data-call=&quot;headerClick&quot;to our a tags so we can do this. We will also need to add the headerClick function to handle the event.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbeba34868e11ac74c4aeb68e69c50d8/href">https://medium.com/media/cbeba34868e11ac74c4aeb68e69c50d8/href</a></iframe><p>Remember calling setState will call render(), so we don’t need to explicitly call render() here. Let’s see our table with the sorting and icons working.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-11%3Fctl%3D1%26embed%3D1%26file%3DTable.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-11%3Fctl%3D1%26embed%3D1%26file%3DTable.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/898e43310e8e088f35a63be135892d5e/href">https://medium.com/media/898e43310e8e088f35a63be135892d5e/href</a></iframe><h3>Footer</h3><p>Then at the bottom of the table, we will add our footer.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd529021022904a151b590007d69e762/href">https://medium.com/media/dd529021022904a151b590007d69e762/href</a></iframe><p>Nothing fancy here. Aaannddd we are done… or at least we replicated the component we had with custom elements. This is no small thing. Now, we can just use &lt;hyper-table&gt; with some &lt;hyper-column&gt; inside and you have a simple yet functional table.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-12%3Fctl%3D1%26embed%3D1%26file%3DTable.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-12%3Fctl%3D1%26embed%3D1%26file%3DTable.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/c82fe7d29f1b1a1d1190bc2417c97862/href">https://medium.com/media/c82fe7d29f1b1a1d1190bc2417c97862/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*UrLtjrYjonasE97oiL6f8A.jpeg" /></figure><h3>Customization</h3><p>Every good table should be able to add/update/remove columns, right? Glad you asked! Let’s add some functions to our table that will allow us to do just that.</p><p>First let’s add to our column element a new attribute called name. This will be used to update/remove columns. If no name is passed we’ll just use the attribute.</p><h4>addColumn</h4><p>We will let the developer add a column by passing a new &lt;hyper-column&gt; . We’ll also allow an object to be passed with the attributes needed. This will update our columns array.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7acac5e1caf51d234ce42cb71191c748/href">https://medium.com/media/7acac5e1caf51d234ce42cb71191c748/href</a></iframe><h4>removeColumn</h4><p>Based on the newly added name to the column, we can easily remove columns from the table. In theory we could use index instead of name, but I wanted to show that we can do either with the elements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8e1c77824b9607afbdbd950e60638ba/href">https://medium.com/media/a8e1c77824b9607afbdbd950e60638ba/href</a></iframe><h4>updateColumn</h4><p>Again using the name attribute, we can update the column details.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/39fa9e09cb1341fb768b3dfe0198803f/href">https://medium.com/media/39fa9e09cb1341fb768b3dfe0198803f/href</a></iframe><p>Let’s see how it looks:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-13%3Fctl%3D1%26embed%3D1%26file%3DTable.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-13%3Fctl%3D1%26embed%3D1%26file%3DTable.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cc26e01ed0297d98c613cde0625b2bf/href">https://medium.com/media/7cc26e01ed0297d98c613cde0625b2bf/href</a></iframe><p>Well, that was easy, and we enhanced our table with very useful functionality!.</p><p>Now you are a custom element/hyperHTML master :D. Or, at least you can start creating your own elements! In the next part we are going to add testing to our table element and maybe add the ability to filter the table display. Please send us your feedback to improve this tutorial.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9a3db4278666" width="1" height="1" alt=""><hr><p><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-6-9a3db4278666">Easy apps with hyperHTML — 6</a> was originally published in <a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Easy apps with hyperHTML — 5]]></title>
            <link>https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-5-f6074f373fa6?source=rss-67b1440c1d52------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6074f373fa6</guid>
            <category><![CDATA[english]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[hyperhtml]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ivan Torres]]></dc:creator>
            <pubDate>Tue, 04 Sep 2018 14:11:41 GMT</pubDate>
            <atom:updated>2019-04-10T16:51:14.449Z</atom:updated>
            <content:encoded><![CDATA[<p>Custom elements</p><p><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-5-402970bf26b4">Version en español</a></p><p><a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a></p><ol><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-1-4a56acad9327">Introduction, wire/bind</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-2-1d60fd41bb67">Events and components</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-3-fdc3610fd9e3">Moar about components and simple state management</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-4-31f769e01135">Wire types and custom definitions (intents)</a></li><li><strong>Custom elements with hyper</strong></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-6-9a3db4278666">Customizing my custom elements</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-7-73d9057e1666">Testing!</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-8-d8a01a5fd1c1">Async loading, placeholder and a Typeahead with hyper</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-9-59ee112be119">Handling routes</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-10-232bee0ce501">3rd party libraries</a></li></ol><p>Part 5 written by <a href="https://medium.com/u/67b1440c1d52">Ivan Torres</a> and <a href="https://medium.com/u/51448e0bd275">Paul Thompson</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*K3i9-YAhQZ7mMwXki57X5g.jpeg" /></figure><h3>My very own tag</h3><p>If you’ve been developing web pages or apps for any amount of time, chances are you’ve seen custom components or HTML tags, especially if you’ve worked with one of the newer JavaScript frameworks. Whatever the name, these components usually all have a similar goal: encapsulate functions and logic into re-usable chunks of code. After a lot of discussion and development by the community, we finally brought these ideas under the canopy of <a href="https://developer.mozilla.org/en-US/docs/Web/Web_Components">Web Components</a>.</p><blockquote>Web Components is a suite of different technologies allowing you to create reusable custom elements — with their functionality encapsulated away from the rest of your code — and utilize them in your web apps. — MDN</blockquote><p>In order to achieve this, the specification addresses the following technologies:</p><ol><li><strong>Custom elements</strong>: A set of JavaScript APIs that lets you define the logic of the element. You can create a function like open() and then you can just call that function from the element document.querySelector(‘custom-dialog’).open().</li><li><strong>Shadow Dom</strong>: Utilizing the shadow DOM enables you to use other HTML elements inside your custom element, even other custom elements! Whatever code is inside the custom element with shadow DOM enabled will be rendered and styled separately. This can be both a bug and a feature, depending on your use case.</li><li><strong>HTML templates</strong>: Two tags &lt;template&gt; and &lt;slot&gt; let you write HTML inside the custom element, but they are not rendered or displayed until you activate them. &lt;template&gt; and &lt;slot&gt; can also be re-used for other things.</li></ol><p>Not every one of these are ready to use in all browsers, and certain aspects are harder to polyfill than others, but we are getting close.</p><p>For now we will concentrate on the basics of custom elements, but at the end we’ll show you how to use the shadow DOM. We’ll also see that hyperHTML can create highly efficient templates. We’ll be able to do everything with hyperHTML that &lt;template&gt; can, except for native use of &lt;slot&gt;.</p><h4>&lt;custom-element awesome=”true”&gt;</h4><p>To get started making custom elements, we need need 3 things:</p><ol><li>A browser that supports custom elements, or a polyfill. We recommend using <a href="https://github.com/WebReflection/document-register-element">document-register-element</a>. This polyfill has been used in production for a while by projects like amp. Alternatively, Google also has a polyfill worth checking out.</li><li>A class that extends the HTMLElement object. This class will contain all the logic for our element. We can also extend from a normal HTML element.</li><li>Finally, we will need to “define” the element. This is how we’ll register our element in the browser, and give it a name.</li></ol><p>In 2 above, we mentioned that there are two ways to extend your custom element class, either by extending HTMLElement, or a build-in HTML tag like span. When we extend HTMLElement, our custom element will be autonomous. However, extending built-ins is a bit controversial, and while the specs describe how to do it, not all browsers are on board. We will see how do both, but for our use case in this blog we are only going to extend from HTMLElement.</p><p>Enough jibber-jabber, show me the code!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-01%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-01%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/51d4bf26561358dee56459613d4b9267/href">https://medium.com/media/51d4bf26561358dee56459613d4b9267/href</a></iframe><p>(A tiny, huge thing in the index.html, since Stackblitz is automagically transpiling our code, we need to include the es5-adapter)</p><p>Lets dissect the code a bit:</p><p>First we name our class and extend HTMLElement. This will be an autonomous element. Then, we have a function called connectedCallback(). ConnectedCallback() will be called after the browser has appended the custom element to the document. We’ll talk more about the custom element lifecycle later on. Inside connectedCallback() we are just adding text to our custom element.</p><p>On line 9 we are defining our element name. Whatever name you choose, you must include a hyphen. In our case, to use this element in HTML we will use the tag &lt;custom-element&gt;&lt;/custom-element&gt;. The define function also takes a second parameter which is the class describing the element.</p><p>Internally, the browser keeps a registry of all the custom elements we define. One of the things we can do with the <a href="https://developer.mozilla.org/en-US/docs/Web/API/CustomElementRegistry">CustomElementRegistry</a> is wait for the elements to be defined. However, we can do a lot of other things. So be sure to take a look at the docs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/325/1*Uf6yUZuRXXKeYHFL8jabYg.jpeg" /></figure><p>Just for funz lets see how to extend a built-in:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-02%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-02%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3e30ef84d50a0d86f8f597911ab9eb8e/href">https://medium.com/media/3e30ef84d50a0d86f8f597911ab9eb8e/href</a></iframe><h4>Life cycle</h4><p>Besides connectedCallback()there are other lifecycle hooks we can use. Let’s see what they do:</p><ul><li><strong>connectedCallback</strong>: called when your element is connected to the document DOM.</li><li><strong>disconnectedCallback</strong>: called when your element is detached from the DOM. You will be able to react to that disconnection in this function.</li><li><strong>adoptedCallback</strong>: is called when you move the element to a new page.</li><li><strong>attributeChangedCallback</strong>: this is called whenever attributes that you are monitoring change. Not every attribute on your custom element will automatically be monitored. To pick which attributes are, you will have to add another function:</li></ul><pre>static get observedAttributes() {return [&#39;attr1&#39;, &#39;attr2&#39;]; }</pre><p>Let’s see these functions in action in our custom-element:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-03%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-03%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/71e029320471be9409f93c06dc3db2ff/href">https://medium.com/media/71e029320471be9409f93c06dc3db2ff/href</a></iframe><p>This cool! We’re well on our way to having a powerful new element. But what about templating? With hyperHTML, we can render whatever we want inside the element and boom, custom elements with all the power of hyperHTML :D</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/220/1*oQV46mV2KLACQJMUNZ6WjA.gif" /></figure><p>Let’s make a few changes. Of course, we first need to load hyperHTML. Then we will bind to the current element with this.html = bind(this); We also need a render() function which will be charged with rendering the template. And finally, we need to update our attributeChangedCallback() to change new attribute values to actual properties:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-04%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-04%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa906b43387d01b4526dbe89990cf9b9/href">https://medium.com/media/aa906b43387d01b4526dbe89990cf9b9/href</a></iframe><h3>Enter hyperHTML-element</h3><p>There is a lot more to learn about custom elements, but fortunately the master <a href="https://medium.com/u/cc83da4b8256">Andrea Giammarchi</a> created another utility that abstracts much of the custom element API. It’s called <a href="https://github.com/WebReflection/hyperHTML-element">hyperHTML-element</a>.</p><p>This is a class that you can extend instead of the HTMLElement, and it gives you a few new functions and properties.</p><h4>Functions</h4><ul><li>Besides the regular observedAttributes we now also have booleanAttributes. This is where we’ll want to put the attributes that don’t need an actual value. For example, &lt;custom-element required&gt;. “Required” either exists or it doesn’t, so it is a great candidate for being a boolean attribute.</li><li>observedAttributes and booleanAttributes both will also define getters and setters for every attribute observed. This means we no longer need to do this[name] = newValue inside attributeChangedCallback.</li><li>created. This is a new callback that will be invoked right before connectedCallback or attributeChangedCallback</li><li>defaultState(). Whenever you use this.state, the defaultState() function returns an object that becomes, you guessed it, the default state.</li><li>setState. Updates the state object (you don’t need to define defaultState to use setState). setState includes a little bonus: it will call render() for you, so your element is automatically updated when you change its state!</li><li>render(). This function should return the HTML you want to display inside your custom element.</li><li>Event handlers. In your template, we can now pass ‘this’ to our event handlers: &lt;div onclick=${this}&gt;&lt;/div&gt; . If we then define an onclick function inside the element, it will get called with the proper context. You can also use data-call to call any function: data-call=onAnyEvent onclick=${this}… in this case onAnyEvent will be called when a user clicks. Even more cool, custom events are super easy: onMyCustomEvent=${this} and you define a onMyCustomEvent(e) function, done!</li><li>define()This static method is just a helper. Instead of using customElements.define you use this one MyElement.define(&#39;my-element&#39;)</li><li>All the hyperHTML functions, bind, component and wire. The only hyper function we don’t get is define for intents, since we’re already using it to register the element. To define intents you will use HyperHTMLElement.intent(…). We looked at intents in another part 4 of this blog, so be sure to brush up on them if you need to.</li></ul><p>Observant readers will notice some of these functions are used in hyper.Component . Hopefully you are familiar with some of them now :D</p><h4>Properties</h4><ul><li>this.html. In our example above we did this.html = bind(this); in the constructor. With hyperHTML-elemet we now can usethis.html directly.</li><li>state. State is an object that holds the…er…state of the element. It’s empty by default, or it will hold whatever object is returned by defaultState, if you’ve defined that function.</li><li>As mention before, every attribute inobservedAttributes and booleanAttributes will have its getter and setter, so you can use this.attr and the value will reflect the attribute. For example, &lt;my-element parent=&quot;your mom&quot;/&gt;, using this.parent will give you the value, “your mom.”</li></ul><p>Sweet! Let’s update our previous element to use all of these new features:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-05%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-05%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fddcb66cd4af27ffe38bc5f8402148a9/href">https://medium.com/media/fddcb66cd4af27ffe38bc5f8402148a9/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*TTLxQoccKUZvMDwsgPJO1A.gif" /></figure><p>What about the shadow DOM?… oh yeah, it’s super easy:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-06%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fintermediate-ce-06%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/87d993ac9c16a6c4b898506bdb050024/href">https://medium.com/media/87d993ac9c16a6c4b898506bdb050024/href</a></iframe><p>Check line 8 this.attachShadow({mode: ‘open’});, if you inspect the element you’ll see that the shadow DOM is there!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*Vtc8-XOraDyHOO5Ar741Rg.png" /></figure><p>There is more to learn about custom elements and web components in general. In the next part we will write some custom logic and update our table from <a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-4-31f769e01135">part 4</a> to be a custom element. And as always, feedback is welcome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6074f373fa6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-5-f6074f373fa6">Easy apps with hyperHTML — 5</a> was originally published in <a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aplicaciones fáciles con hyperHTML — 3]]></title>
            <link>https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-3-fc4a0503f498?source=rss-67b1440c1d52------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc4a0503f498</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[español]]></category>
            <category><![CDATA[hyperhtml]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ivan Torres]]></dc:creator>
            <pubDate>Fri, 24 Aug 2018 00:39:22 GMT</pubDate>
            <atom:updated>2018-11-09T20:42:34.401Z</atom:updated>
            <content:encoded><![CDATA[<p>Mas acerca de componentes y manejo de estado</p><p><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-3-fdc3610fd9e3">English Version</a></p><p>Parte 3 escrita por <a href="https://medium.com/u/67b1440c1d52">Ivan Torres</a> y <a href="https://medium.com/u/51448e0bd275">Paul Thompson</a>.</p><p>Traducción por <a href="https://medium.com/u/2fc7b2a1d87c">Lupita Hernandez</a> e <a href="https://medium.com/u/67b1440c1d52">Ivan Torres</a></p><p><a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a></p><ol><li><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-1-5b887e042c47">Introducción, wire/bind</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-2-dd264fa495e5">Eventos y componentes</a></li><li><strong>Más acerca de componentes y manejo de estado simple</strong></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-4-785f5d35f895">Tipos de <em>wires</em> y definiciones personalizadas (<em>intents</em>)</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-5-402970bf26b4"><em>Custom elements</em> con hyper</a></li><li>Personalizando mis <em>custom elements</em></li><li>Corriendo pruebas!</li><li>Carga asíncrona, <em>placeholder </em>y un <em>Typeahead</em> con hyper</li><li>Manejando rutas</li><li>Usando librerías externas (<em>3rd party</em>)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*YtN66eBFlRmBFarPGPBqqQ.jpeg" /></figure><p>En la <a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-2-dd264fa495e5">parte 2</a>, usamos <em>hyper Components </em>para crear una tabla que se puede ordenar. Antes de añadir más cosas a nuestra tabla, vamos a ver el código que llevamos hasta ahorita.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-5%3Fembed%3D1&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-5&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/14920e7505e7ab322f3ff323bdc34358/href">https://medium.com/media/14920e7505e7ab322f3ff323bdc34358/href</a></iframe><h3><strong>Componentes de la tabla</strong></h3><p>Te diste cuenta que hay partes del código que podemos reusar? Si lo reestructuramos, podemos usar partes para otras tablas y ademas de que sera mas facil de mantener al solo tener que actualizar la parte necesaria en lugar de todo. Las siguientes partes son buenos candidatos para separar:</p><ul><li>La definicion de la tabla en general</li><li>La cabecera (renglones y columnas)</li><li>El cuerpo de la tabla</li><li>El pie de la tabla… no tenemos uno pero se lo vamos a agregar nomas para divertirnos un poco</li></ul><p>Veamos cómo podemos cambiar estas partes para tener un código que sea mas fácil de actualizar y reusar.</p><h4>Tabla</h4><p>Primero, vamos a crear el archivo <em>Table.js </em>y mover la mayoría del código aquí. No vamos a necesitar el uso de la función <em>bind()</em> en este archivo, en su lugar solo vamos a exportar la clase <em>Table</em>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-5-1%3Fembed%3D1%26file%3DTable.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-5-1%3Ffile%3DTable.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce52ec4e7de5206fc74b672d38e031a9/href">https://medium.com/media/ce52ec4e7de5206fc74b672d38e031a9/href</a></iframe><p>Después, vamos a actualizar <em>index.js </em>para importar nuestra tabla. Aquí es donde usaremos la función <em>bind()</em>. Recuerda que <em>bind()</em> funciona en nodos existentes como <em>document.body</em>. También date cuenta como estamos pasando la information a la clase <em>Table</em>: a través de un objecto en el constructor.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-5-1%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-5-1%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/7801bdc14ce1bb4df27661079e3be508/href">https://medium.com/media/7801bdc14ce1bb4df27661079e3be508/href</a></iframe><h4>Cabecera</h4><p>Nuestra clase <em>Header </em>también extenderá <em>Component.</em></p><p>Primero ahí que mover el elemento &lt;thead&gt; de nuestra tabla a la función <em>render()</em>, así se vera render en <em>Header:</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bd021052a945c7d281c9446d6b75c1e/href">https://medium.com/media/9bd021052a945c7d281c9446d6b75c1e/href</a></iframe><p>En esta plantilla estamos escuchando el evento <em>onclick</em> en los elementos &lt;th&gt;. Como no queremos manejar el estado en esta clase, vamos a disparar un evento <em>Custom</em> llamado <em>sort</em>. Este evento va a tener algunos detalles como en cual columna esta el usuario ordenando y si es ascendente o descendiente.</p><p>Vamos a añadir una función <em>update</em> también. Al usar esta función, podemos estar seguros que siempre estamos usando los datos mas actuales. Si los datos cambian en el componente padre, nuestra cabecera va a recibir los nuevos datos. Esta se vera así:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c072cc83d9709a73e4da5ba736601d6/href">https://medium.com/media/1c072cc83d9709a73e4da5ba736601d6/href</a></iframe><p><em>Dispatch</em> es una función incluida en <em>Component</em>. Va a crear un evento <em>custom </em>con su nombre basado en el primer parámetro, y los detalles de este basado en el segundo parámetro. Esta es una función muy util. Aprende mas acera de dispatch() en la <a href="https://viperhtml.js.org/hyperhtml/documentation/#components-3">documentación</a> oficial (e ingles). Nuestra función <em>onclick</em> se ve ahora así:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6e2f5cb7c3c861c6a5f13560caf355f0/href">https://medium.com/media/6e2f5cb7c3c861c6a5f13560caf355f0/href</a></iframe><p>Y así se ve nuestra clase Header:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-5-2%3Fembed%3D1%26file%3DHeader.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-5-2%3Ffile%3DHeader.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebeb8683f5892c20adacd37fc4e6aa01/href">https://medium.com/media/ebeb8683f5892c20adacd37fc4e6aa01/href</a></iframe><p>Ahora vamos a actualizar la clase <em>Table </em>para cargar nuestro componente <em>Header. </em>Vamos a importarlo otra vez igual que antes. Después, en lugar de el elemento &lt;thead&gt; en la función <em>render(), </em>vamos a usar la clase <em>Header</em>:</p><p>${Header.for(this).update(this.state)}.</p><p><em>Component.for</em> es una utilidad que te deja crear componentes directamente en <em>render()</em>. En lugar de crear el componente en alguna otra función, puedes crearlo aquí mismo. <em>Header.for(object) </em>va a enlazar la cabecera al objeto pasado, en este caso a nuestra clase <em>Table</em>, después llamamos la función <em>update </em>para actualizar la plantilla de la cabecera con el estado actual, esta sera pasado en cada llamado a <em>render()</em>. Vamos a usar otras formas de iniciar los componentes después. Lee mas sobre <em>for()</em> en la <a href="https://viperhtml.js.org/hyperhtml/documentation/#components-3">documentación</a>.</p><p>Como ultimo paso, vamos a añadir la función <em>onsort</em> a la tabla para manejar el evento de ordenación: onsort=&quot;${this}&quot;. Esta función va a escuchar cuando el evento <em>sort </em>sea enviado por la cabecera. Necesitamos cambiar la función onclick a onsort, a la vez que la simplificaremos un poco. La información acerca de como ordenar los datos viene en el objeto dentro de la propiedad <em>detail</em> del evento. Con esto podemos ordenar los datos como antes y actualizar el estado de la tabla. Recuerda que estamos pasando el estado hacia la clase <em>Header</em> desde la clase <em>Table</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/862f0b9b92c599b36fa5c980d178ae2c/href">https://medium.com/media/862f0b9b92c599b36fa5c980d178ae2c/href</a></iframe><p>Vamos a ver el código que llevamos hasta el momento:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-5-2%3Fembed%3D1%26file%3DTable.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-5-2%3Ffile%3DTable.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9bdf7e617e4ae2e10b7cd99070404bd/href">https://medium.com/media/d9bdf7e617e4ae2e10b7cd99070404bd/href</a></iframe><h4>Body</h4><p>Para nuestro componente del cuerpo de la tabla, vamos a seguir los mismos pasos, mover el elemento tbody de la función render() de la clase <em>Table</em> a nuestro nuevo componente llamado <em>Body. Body</em> tendrá su propia función de render() de la siguiente forma:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a78d1a237f59d566fec6a4891817af3/href">https://medium.com/media/8a78d1a237f59d566fec6a4891817af3/href</a></iframe><p>Aunque es el componente que contiene la mayor información de nuestra tabla, es bastante compacto en cuanto a código, vamos a ver el archivo completo:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-5-3%3Fembed%3D1%26file%3DBody.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-5-3%3Ffile%3DBody.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa302716f5985c220ba4d60beaaea319/href">https://medium.com/media/fa302716f5985c220ba4d60beaaea319/href</a></iframe><p>Pon atención a la linea:</p><p>this.props = props;</p><p>Vamos a usar esto para pasar los datos a nuestro componente <em>Body</em>. La información que pasemos sera la que usaremos en la plantilla.</p><p>Ahora, vamos a actualizar la clase <em>Table</em> para cargar el componente <em>Body</em>, usando <em>import</em> como antes.</p><p>import { Body } from &#39;./Body&#39;;</p><p>Para este componente, vamos a hacerlo un poco diferente. En lugar de usar <em>Component.for</em>, vamos a crear la instancia de este en el constructor. No necesitamos pasar datos en la creación.</p><p>this.body = new Body();</p><p>Con esto vamos a tener una tabla que funciona correctamente. Va a ordenarse, pero no estamos cambiando el arreglo (añadir o remover). Pero que tal si nuestros datos si cambian?. Podemos agregar la función <em>update(props)</em> en <em>Body</em> para recibir nuevos datos, justo como en <em>Header</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1c072cc83d9709a73e4da5ba736601d6/href">https://medium.com/media/1c072cc83d9709a73e4da5ba736601d6/href</a></iframe><p>De esta forma siempre vamos a recibir los datos mas actuales desde la clase <em>Table</em>. Ahora podemos llamar <em>update()</em> directamente:</p><p>this.body.update(this.data)</p><p>Vamos a ver todo el código hasta ahora:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-5-4%3Fembed%3D1%26file%3DTable.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-5-4%3Ffile%3DTable.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfc49c24fb02a8466509cf72d12ef0a8/href">https://medium.com/media/dfc49c24fb02a8466509cf72d12ef0a8/href</a></iframe><p><strong>Footer</strong></p><p>Como lo prometido es deuda… vamos a agregar el pie de la tabla. Vamos a mostrar el numero total de columnas en este. Ademas de los elementos html para el tfoot, no hay nada nuevo en esta clase. Vamos a revisarla:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-6%3Fembed%3D1%26file%3DFooter.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-6%3Ffile%3DFooter.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/c720926be45440f1369d4812cf05d18c/href">https://medium.com/media/c720926be45440f1369d4812cf05d18c/href</a></iframe><p>Como siempre vamos a actualizar la clase <em>Table </em>para cargar el componente <em>Footer</em>. Usaremos <em>Component.for</em> y la función update() para así siempre recibir los datos mas actuales, de otra forma nuestra cuenta no seria correcta.</p><p>Footer.for(this).update(this.data).</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-6%3Fembed%3D1%26file%3DTable.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-6%3Ffile%3DTable.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/f79b57ce40f368da51b588fd1d291c33/href">https://medium.com/media/f79b57ce40f368da51b588fd1d291c33/href</a></iframe><p>Yyyyy listo! Tenemos nuestra simple tabla con un manejo de estado simple: pasamos los datos hacia abajo y los eventos hacia arriba. Podríamos haber usado una librería para manejar el estado como <em>Redux </em>o<em> Flux.</em> Para nuestra tabla, realmente no necesitamos usar nada mas complejo que lo que tenemos.</p><p>Antes de ver la parte 4, exploremos una pequeña librería llamada <a href="https://proppyjs.com/"><em>ProppyJS</em></a><em>.</em> Esta no es una librería para el manejo de estado, pero si una librería que nos permite componer propiedades. De esta manera podemos componer las propiedades de varias fuentes y usarlas en cualquier componente. No estamos dando una gran libertad en nuestras aplicaciones, manteniendo separados las propiedades de los componentes. Con ProppyJS, podemos agregar un <em>store Redux</em> si así lo necesitamos después cuando el estado de nuestro componente se vuelva mas complejo.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-6-p%3Fembed%3D1%26file%3DPropFactory.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-6-p%3Ffile%3DPropFactory.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/f62352535cca782267e32d14e23e1627/href">https://medium.com/media/f62352535cca782267e32d14e23e1627/href</a></iframe><p>Creamos una clase donde generamos las propiedades y la llamamos p, usándola en todos los componentes. Nuestro componente fue disminuido bastante y ahora la cabecera esta actualizando el ordenamiento directamente. Deja un comentario abajo si tienes preguntas sobre la implementación de <em>ProppyJS</em> en el código.</p><p>Queremos que estos tutoriales sean lo mejor que se puedan para ti! Si tienes retroalimentacion para nosotros, por favor déjalo en los comentarios. Gracias por leernos y sigue alerta a la siguiente parte donde exploraremos una característica poderosa llamada “<em>intents”</em>. Estos nos dejan expandir <em>hyperHTML</em> con definiciones personalizadas para nuestras plantillas.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc4a0503f498" width="1" height="1" alt=""><hr><p><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-3-fc4a0503f498">Aplicaciones fáciles con hyperHTML — 3</a> was originally published in <a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Aplicaciones fáciles con hyperHTML — 2]]></title>
            <link>https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-2-dd264fa495e5?source=rss-67b1440c1d52------2</link>
            <guid isPermaLink="false">https://medium.com/p/dd264fa495e5</guid>
            <category><![CDATA[español]]></category>
            <category><![CDATA[desarrollo-web]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[hyperhtml]]></category>
            <dc:creator><![CDATA[Ivan Torres]]></dc:creator>
            <pubDate>Sat, 11 Aug 2018 03:18:51 GMT</pubDate>
            <atom:updated>2018-11-09T20:43:04.032Z</atom:updated>
            <content:encoded><![CDATA[<p>Eventos y components</p><p><a href="https://medium.com/easy-apps-with-hyperhtml/easy-apps-with-hyperhtml-2-1d60fd41bb67">English Version</a></p><p><a href="http://www.lofter.com/lpost/1f16161f_12b7a08fe">中文版</a></p><p>Parte 2 escrita por <a href="https://medium.com/u/67b1440c1d52">Ivan Torres</a> y <a href="https://medium.com/u/51448e0bd275">Paul Thompson</a>.</p><p>Traducción por <a href="https://medium.com/u/2fc7b2a1d87c">Lupita Hernandez</a> e <a href="https://medium.com/u/67b1440c1d52">Ivan Torres</a></p><p><a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a></p><ol><li><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-1-5b887e042c47">Introducción, wire/bind</a></li><li><strong>Eventos y componentes</strong></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-3-fc4a0503f498">Más acerca de componentes y manejo de estado simple</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-4-785f5d35f895">Tipos de <em>wires</em> y definiciones personalizadas (<em>intents</em>)</a></li><li><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-5-402970bf26b4"><em>Custom elements</em> con hyper</a></li><li>Personalizando mis <em>custom elements</em></li><li>Corriendo pruebas!</li><li>Carga asíncrona, <em>placeholder </em>y un <em>Typeahead</em> con hyper</li><li>Manejando rutas</li><li>Usando librerías externas (<em>3rd party</em>)</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*9xn2AlWR1kZP9p7X_zqMgA.jpeg" /></figure><p>Si seguiste la <a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-1-5b887e042c47">parte 1</a>, ya sabes por ahora lo basico para empezar a trabajar con hyperHTML. Podemos ahora revisar temas mas complejos. Recuerdas la tabla que hicimos en la parte 1:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table%3Fembed%3D1&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/42bbd74658441a55a574c9d86355a8bc/href">https://medium.com/media/42bbd74658441a55a574c9d86355a8bc/href</a></iframe><p>Vamos a empezar habilitando el ordenamiento de las columnas al presionar las cabeceras de la tabla.</p><h3>Eventos</h3><p>Primero, vamos a mover la parte de nuestro ejemplo anterior que contiene la plantilla para que podamos reutilizarla. Empezamos con esto:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57d36366c85ecf94fa207edf900a583e/href">https://medium.com/media/57d36366c85ecf94fa207edf900a583e/href</a></iframe><p>Vamos a cambiar ese código a esto:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7db72c7f6f4f2236909c5b2e317b0a15/href">https://medium.com/media/7db72c7f6f4f2236909c5b2e317b0a15/href</a></iframe><p>La siguiente cosa que tenemos que hacer es actualizar las cabeceras de nuestras columnas para que contengan un elemento &lt;a&gt; para que los usuarios sepan que pueden hacer click en ellas. También vamos a capturar los eventos onclick. Para facilitarnos la vida, vamos a agregar el attribute data-target para saber que esta el usuario intentado ordenar. Con estas partes en su lugar, nuestra plantilla se vera de la siguiente forma:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c63ce71db79e028243b32a51e8d662e/href">https://medium.com/media/6c63ce71db79e028243b32a51e8d662e/href</a></iframe><p>Que significa el código en onclick? hyperHTML nos deja pasa una función al evento y la llamara por nosotros. Vamos a crear una para ordenar los datos:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd5a3cdcb4a9325552aa1e1f95c14f91/href">https://medium.com/media/dd5a3cdcb4a9325552aa1e1f95c14f91/href</a></iframe><p>El <em>target </em>del evento (e) y ‘this’ apuntan al elemento, Muy bien!. Ahora que tenemos nuestro elemento enlace, el cual contiene el atributo data-target, que usaremos para ordenar los datos en la tabla. Vamos a actualizar nuestra función para ordenar:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2b8d3d4dc463d4003674c7f48dbf6876/href">https://medium.com/media/2b8d3d4dc463d4003674c7f48dbf6876/href</a></iframe><p>Mientras todo esta bien y funciona, si el usuario le da click una segunda vez a la misma cabecera, no va a cambiar el sentido del ordenamiento. Esta es la funcionalidad que esperamos tener, vamos a actualizar el código para arreglar eso… revisemos lo que llevamos hasta ahora:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-1%3Fembed%3D1&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-1&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/da8d1e1c05b24538f6ff24d9edbe63e0/href">https://medium.com/media/da8d1e1c05b24538f6ff24d9edbe63e0/href</a></iframe><p>Si inspeccionas el código de la tabla (con el navegador), veras que solo los renglones del cuerpo de la tabla se actualizan con cada click. HyperHTML es lo suficientemente inteligente para solo actualizar las partes que cambiaron, esto demuestra que rápido es y lo “barato” que es utilizar la funcion de <em>render</em>.</p><h3>Componentes</h3><p>Ahora que tenemos nuestra tabla, tal vez sea mas fácil si ponemos todo el código relacionado en un solo lugar. Ademas de limpiarlo, vamos a poder reutilizar esta tabla en otros projectos. Podemos lograr esto con un simple objeto:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-2%3Fembed%3D1&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-2&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fe8ab125e2a8a00ef233e8238727620/href">https://medium.com/media/3fe8ab125e2a8a00ef233e8238727620/href</a></iframe><p>Tenemos un objeto básico de JavaScript con los siguientes atributos: html como nuestra variable que contiene la función para procesar la plantilla, <em>data </em>que es nuestro arreglo con los datos para la table y <em>state </em>que mantiene el estado actual de la tabla. Movimos render() afuera de la función display(), date cuenta que ya no tenemos sort(). En su lugar pasamos ‘this’ al evento onclick.</p><p>onclick=${this}</p><p>y lo manejas con…</p><h4>HandleEvent</h4><p>Esta función especial es parte del estándar <em>EcmaScript</em>. Si un objeto contiene esta, sera llamada de la siguiente forma obj.handleEvent(e). Esto significa que podemos vincular una función para manejar el evento:</p><p>el.addEventListener(&#39;click&#39;, Table)</p><p>y el evento <em>click </em>sera pasado a <em>handleEvent</em>. this sera el objeto actual (no el elemento!). Esto resuelve algunos de los típicos problemas que nos encontramos cuando estamos manejando eventos. Para mas información sobre la asombrosa <em>handleEvent </em>hazlo en el siguiente enlace <a href="https://medium.com/@WebReflection/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38">https://medium.com/@WebReflection/dom-handleevent-a-cross-platform-standard-since-year-2000-5bf17287fd38</a></p><p>En nuestro caso, estamos pasando el objeto actual a <em>handleEvent</em>. Ahora, solo moveremos toda la funcionalidad de ordenamiento adentro de esta función. Claro que podemos hacer mas cosas con esto, pero por ahora así nos da la funcionalidad que necesitamos para ordenar los datos de la tabla.</p><p>También puedes usar una función para construir tu objeto, justo como esperas que funcione.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-3%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-3%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1b1004b337904b4436b623d450c8b3c/href">https://medium.com/media/d1b1004b337904b4436b623d450c8b3c/href</a></iframe><p>Prácticamente lo mismo que antes, el único cambio es que agregamos un <em>Id </em>(identificador) a la tabla. Si no quieres usar clases, puedes usar este acercamiento y hyperHTML no se interpondrá en tu camino.</p><h4>Clases</h4><p>“Todo eso esta bien pero y las clases de ES6?” tal vez te estas preguntando. Bueno, también puedes usarlas.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-4%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-4%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/33578a340474921ffc94de4e3504c915/href">https://medium.com/media/33578a340474921ffc94de4e3504c915/href</a></iframe><p>Y ahora ya tienes una clase, la única cosa que cambias (ademas de convertirlo a una clase) fue la forma de pasar las propiedades, en lugar de pasar una cadena de caracteres, pasamos el identificador (id) adentro de un objeto. Nada fuera de lo común, esto solo nos ayuda para mejorar el código después.</p><p>Y si, hyperHTML también tiene una forma muy sencilla de crear componentes. Se llama <em>hyper.Component</em>. Esta función te da algunas cosas extras que veras son muy útiles:</p><ul><li>Manejo de estado</li><li>por defecto el atributo html enlazado asi mismo.</li><li><em>handleEvent</em>, pero mas fácil!</li><li>funciones para los eventos onconnected y ondisconnected</li><li>y mas</li></ul><p>Para mas información acerca de hyper.Component puedes leer la documentación oficial(en ingles) <a href="https://viperhtml.js.org/hyperhtml/documentation/#components-3">https://viperhtml.js.org/hyperhtml/documentation/#components-3</a></p><p>Suficiente de vender la idea, vamos a ver un ejemplo usando todas las cosas!!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-5%3Fembed%3D1%26file%3Dindex.js&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fbasics-table-5%3Ffile%3Dindex.js&amp;image=https%3A%2F%2Fc.staticblitz.com%2Fassets%2Ficon-664493542621427cc8adae5e8f50d632f87aaa6ea1ce5b01e9a3d05b57940a9f.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=stackblitz" width="745" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/adc86c4343ce9a44f67f5662ed002b93/href">https://medium.com/media/adc86c4343ce9a44f67f5662ed002b93/href</a></iframe><p>Primero, agregamos <em>Component </em>donde importamos hyperHTML (<em>Component </em>es hyper.Component), después hacemos que la clase Table lo extienda. Como la clase <em>Component </em>también provee la propiedad “html”, removimos “this.html” de nuestra clase.</p><h4>Manejando eventos con Component</h4><p>Donde esta nuestra función <em>handleEvent</em>?, bueno pues <em>Component </em>ya lo implementa así que tampoco lo necesitamos!. La forma en que <em>Component </em>define <em>handleEvent</em> es:</p><p>this[‘on’ + event.type](e)</p><p>Esto significa que si quieres agregar una función que reaccione al evento onclick, <em>handleEvent </em>va a recibir el evento con tipo “click” y va a invocar this.onclick(e), asi que ahora podemos tener funciones por tipo de evento, por ejemploonclick(e) {…}.</p><p>También puedes definir funciones para manejar eventos <em>Custom!</em>, por ejemplo, digamos que algo esta emitiendo el evento “enroll”, puedes agregar un evento de la siguiente forma:</p><p>onenroll=${this}</p><p>y después manejar agregando una función a la clase así:</p><p>onenroll(e){ /* codigo para manejar inscripcion (enroll) */}</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a8bb15b088eb88c6674af6ba9ca50f37/href">https://medium.com/media/a8bb15b088eb88c6674af6ba9ca50f37/href</a></iframe><p>De regreso a nuestra Tabla, ahora tenemos nuestroonclick para manejar el evento “click” en las cabeceras de las columnas y hacer el ordenamiento.</p><h4>Estado</h4><p>Date cuenta que agregamos get defaultState(){...}. Esta es una función que regresa el estado inicial, así que si no has actualizado o cambiado el estado, vamos a recibir lo que se encuentre en este objeto adentro de esta. Lee mas acerca de <em>defaultState </em>en la <a href="https://viperhtml.js.org/hyperhtml/documentation/#components-3">documentación</a></p><p>También en onclick (que usamos para ordenar) agregamos setState, esta llamada va a actualizar el objeto donde guardamos el estado con el objeto que estemos pasando y ademas va a invocar automáticamente la función render() para actualizar la plantilla. Otros <em>frameworks </em>van a actualizar el estado de manera asíncrona por “razones”, pero como las actualizaciones son muy rápidas con hyperHTML, <em>setState </em>invocara render() inmediatamente. De todas formas si necesitas actualizar varias cosas del estado te recomiendo construir un objeto y después invocar <em>setState </em>con el nuevo objeto setState(newobj).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0482e741248b733df04a0b99ae36465d/href">https://medium.com/media/0482e741248b733df04a0b99ae36465d/href</a></iframe><p>Vimos mucho código en esta parte. Apenas estamos empezando a profundizar en hyperHTML. En la siguiente parte, veremos como utilizar varios componentes en una sola aplicación, como actualizar condicionalmente partes de la plantilla y aun mas detalles sobre los componentes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dd264fa495e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/easy-apps-with-hyperhtml/aplicaciones-f%C3%A1ciles-con-hyperhtml-2-dd264fa495e5">Aplicaciones fáciles con hyperHTML — 2</a> was originally published in <a href="https://medium.com/easy-apps-with-hyperhtml">Easy apps with hyperHTML</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>