<?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 Danny Blue on Medium]]></title>
        <description><![CDATA[Stories by Danny Blue on Medium]]></description>
        <link>https://medium.com/@deebloo?source=rss-882e20165484------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*2vyqIpTNjtH5MxFPHU7huw.jpeg</url>
            <title>Stories by Danny Blue on Medium</title>
            <link>https://medium.com/@deebloo?source=rss-882e20165484------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 17:14:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@deebloo/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[Unique Api Hooks using Symbols]]></title>
            <link>https://itnext.io/unique-api-hooks-using-symbols-1f09f770e6d2?source=rss-882e20165484------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f09f770e6d2</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Danny Blue]]></dc:creator>
            <pubDate>Wed, 24 Jul 2024 20:12:24 GMT</pubDate>
            <atom:updated>2024-07-24T21:05:17.770Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zrf2P_qh9sRieLjCcN4YtA.png" /></figure><p>Naming things is one of the hardest problems in computer science, in almost no place have I found this to be more true and when defining life-cycle hooks. I most recently ran into this problem when defining hooks for my dependency injection library <a href="https://github.com/joist-framework/joist/tree/main/packages/di">@joist/di</a>. I found the most challenging method to name to be the dreaded “init” method. In Joist it would look something like below.</p><pre>class MyService {<br>  onInit() {<br>    // service initialized!<br>  }<br>}</pre><p>This seems like an easy answer! However, this is a VERY generic name and could pretty easily create a conflict. When we look at other libraries with similar hooks we notice something specific about their APIs. Take Angular for example.</p><pre>@Component()<br>class MyComponent {<br>  ngOninit() {<br>    // initialized<br>  }<br>}</pre><p>Angular prefixes their life-cycle callbacks with “ng”. This convention helps the user in two ways.</p><ol><li>If a user is reading existing code they know that these methods are part of the Angular framework.</li><li>When a user defines new methods it is very unlikely they would use Angular’s naming convention and cause a conflict.</li></ol><h4>Enter Symbols</h4><p>Symbols are a JavaScript API that creates unique values. The API itself is very simple.</p><pre>const value1 = Symbol(&quot;a value&quot;);<br>const value2 = Symbol(&quot;a value&quot;);<br><br>assert(value1 === value2); // error!</pre><p>Like strings, Symbols can also be used to define properties/fields on JavaScript objects and classes. We can find examples of this in existing JavaScript APIs like Symbol.iterator. This predefined symbol is used to define the iterator method instead of an arbitrarily named method.</p><pre>class MyIterable {<br>  *[Symbol.iterator]() {<br>    yield 1;<br>    yield 2;<br>    yield 3;<br>  }<br>}<br><br>for(let value of new MyIterable()) {<br>  console.log(value)<br>}</pre><p>Something like this would solve our naming problem! Now we can explicitly define method names without worrying about a potential collision. These symbols can be exposed from the package and made available to users.</p><pre>const LifeCycle = {<br>  onInit: Symbol(&#39;onInit&#39;)<br>}<br><br>class MyService {<br>  [LifeCycle.onInit]() {<br>    // service initialized!<br>  }<br>}</pre><p>I prefer this solution to a defined naming convention for several reasons.</p><ol><li>I don’t need to worry about naming collisions.</li><li>I don’t need to describe and document a naming convention that is specific to Joist.</li><li>I can change the symbol behind the scenes without breaking the public facing API</li></ol><p>Symbols feel like one of the JavaScript APIs that you never think about until it solves a very specific problem for you. But what do you think? Are Symbols the appropriate technique for the situations listed above or are well defined naming conventions enough?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f09f770e6d2" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/unique-api-hooks-using-symbols-1f09f770e6d2">Unique Api Hooks using Symbols</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stream-able Web Components and their parent/child relationship]]></title>
            <link>https://itnext.io/stream-able-web-components-and-their-parent-child-relationship-911122f48d50?source=rss-882e20165484------2</link>
            <guid isPermaLink="false">https://medium.com/p/911122f48d50</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-components]]></category>
            <dc:creator><![CDATA[Danny Blue]]></dc:creator>
            <pubDate>Tue, 21 Nov 2023 15:34:23 GMT</pubDate>
            <atom:updated>2024-01-30T16:51:05.266Z</atom:updated>
            <content:encoded><![CDATA[<p>Web components allow developers to provide an HTML interface for JavaScript. Designing your elements to be expressible in HTML will often mean passing children to elements rather than adding properties. For example, for a custom “select” element you probably want to pass options as child elements rather than properties which can only be set with JavaScript.</p><pre>&lt;x-select&gt;<br>  &lt;x-option value=&quot;first&quot;&gt;&lt;/x-option&gt;<br>  &lt;x-option value=&quot;second&quot;&gt;&lt;/x-option&gt;<br>  &lt;x-option value=&quot;third&quot;&gt;&lt;/x-option&gt;<br>&lt;/x-select&gt;</pre><p>For this example we will assume that we are using the native select element under the hood, we just want to reflect our custom options to native ones. While we will be looking at how to build a select menu this technique can be used for any parent element that needs to respond to its children.</p><h4>Why?</h4><p>Before I propose the following solution let’s talk about other potential options available to us, and their particular problems/challenges. I want to solution to solve all of the following</p><ol><li>Provide parent with initial state and notify when children are added and removed.</li><li>Easily identify which children have been added and removed.</li><li>Needs to work exactly the same if the script is loaded before the elements exist or after. This is particularly important, I want the ability to define my custom elements BEFORE the document is parsed.</li></ol><h4>“slotchange” event</h4><p>The slotchange event is great and is probably the first thing to reach for in this situation.</p><ol><li>It fires after the component has been initialized and whenever the assigned children change.</li><li>Does not provide a way to know which nodes have been removed without manually keeping track.</li><li>This DOES work the same for both, but can run into issues if you are depending on child elements being upgrade before the parent.</li></ol><h4>MutationObserver</h4><p>MutationObservers solve a problem not solved by slotchange but still has a couple of things to keep in mind.</p><ol><li>It will only fire when children have changed, this means that if the document is parsed before the elements have upgrade the observer callback will not fire.</li><li>The biggest plus for MutationObserver is that you get two list of nodes. One of nodes that have been added and another of those that have been removed.</li><li>As mentioned in the first item you have to handle init and watching differently based on a number of factors.</li></ol><p>The two solutions above very well may work for your use-case and they are excellent tools. The goal of the below solution is to avoid the potential issues they both have.</p><h4>Child to parent communication</h4><p>What I am really after is the ability for a child element to cleanly notify the parent element that something has changed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/321/1*IM-l_LZVlha8jUuJKbuC5w.png" /></figure><p>Custom Elements come built in with lifecycle callbacks when let us know immediately when our elements have been added to the DOM and when they have been removed from the DOM.</p><p>NOTE: Something like this could also be handled with events but I like the direct relationship calling methods imperatively allows.</p><h4>Step 1: Defining an “option-able” element.</h4><p>An option-able element is an interface that defines an onOptionAdded and onOptionRemoved method. These methods describe what happens when a child is added and removed. This essentially adds two new lifecycle events to your element. I am using TypeScript abstract classes here so I can do instanceOf checks but you can use plain classes.</p><pre>abstract class XOptionableElement extends HTMLElement {<br>  abstract onOptionAdded(item: XOptionElement): void;<br>  abstract onOptionRemoved(item: XOptionElement): void;<br>}</pre><h4>Step 2: Defining an Option</h4><p>An ”option” is a custom element that understands the OptionableElement interface. Since it already knows when it has been added and removed (thanks again lifecycle callback!), all it needs to do is call the appropriate function and pass a reference of itself.</p><pre>class XOptionElement extends HTMLElement {<br>  get value() {<br>    return this.getAttribute(&quot;value&quot;) || &quot;&quot;;<br>  }<br><br>  set value(value: string) {<br>    this.setAttribute(&quot;value&quot;, value);<br>  }<br><br>  #parent: OptionableElement | null = null<br><br>  connectedCallback() {<br>    // when the element has been connected<br>    // check to see if the parent is XOptionableElement<br>    if (this.parentElement instanceof XOptionableElement) {<br>      // If it is we can save it and call the `onOptionAdded` method<br>      this.#parent = this.parentElement;<br>      this.#parent.onOptionAdded(this);<br>    }<br>  }<br><br>  disconnectedCallback() {<br>    // when disconnected we can check if there was a valid parent<br>    // and if so cal the `onOptionRemoved` method<br>    if (this.#parent) {<br>      this.#parent.onOptionRemoved(this);<br>      this.#parent = null;<br>    }<br>  }<br>}<br><br>customElements.define(&quot;x-option&quot;, XOptionElement)</pre><h4>Defining the our select Element</h4><p>Now we need to define how our parent element will react when these two new lifecycles are called. For this example we are going to mirror our x-option to a native option for our select menu.</p><pre>class XSelectElement extends XOptionableElement {<br>  #shadow = this.attachShadow({ mode: &quot;open&quot; });;<br>  #select = document.createElement(&quot;select&quot;);<br><br>  constructor() {<br>    super();<br><br>    this.#shadow.append(this.#select);<br>  }<br><br>  // Define how options are added<br>  onOptionAdded(node: XOptionElement) {<br>    const option = document.createElement(&quot;option&quot;);<br>    option.value = node.value;<br>    option.id = `o-${node.value}`;<br>    option.innerHTML = node.innerHTML;<br><br>    this.#shadow.append(item);<br>  }<br><br>  // Define how options are removed<br>  onOptionRemoved({ value }: XOptionElement) {<br>    const internal = this.#shadow.getElementById(`o-${value}`);<br><br>    internal?.remove();<br>  }<br>}<br><br>customElements.define(&#39;x-select&#39;, XSelectElement);</pre><p>Now let’s revisit our markup and look at what is happening step by step. For the below example we will assume we are defining our custom elements before the document is parsed so we can follow it down.</p><pre>&lt;!-- x-select is defined and is upgraded --&gt;<br>&lt;x-select&gt;</pre><pre>&lt;x-select&gt;<br>  &lt;!-- x-option is upgraded, calls parent onOptionAdded --&gt;<br>  &lt;x-option value=&quot;first&quot;&gt;First&lt;/x-option&gt;</pre><pre>&lt;x-select&gt;<br>  &lt;x-option value=&quot;first&quot;&gt;First&lt;/x-option&gt;<br>  &lt;!--x-option is upgraded, calls parent onOptionAdded --&gt;<br>  &lt;x-option value=&quot;second&quot;&gt;Second&lt;/x-option&gt;</pre><pre>&lt;x-select&gt;<br>  &lt;x-option value=&quot;first&quot;&gt;First&lt;/x-option&gt;<br>  &lt;x-option value=&quot;second&quot;&gt;Second&lt;/x-option&gt;<br>&lt;/x-select&gt;<br>&lt;!-- x-select is closed--&gt;<br>&lt;!-- our select state is already exactly what we want it to be --&gt;</pre><h4>Pros and Cons</h4><p>Pros</p><ul><li>The browser does the iterating. Something to notice above is that we never have to manually iterate through any elements. Since the browser has native lifecycle events we are essentially letting the browser handle iteration for us. Neat!</li><li>HTML as data — since we are using HTML elements to provide data to our parent it is render-able by lots of frameworks. As long as your tool can generate HTML it can generate the appropriate markup</li><li>Parents don’t need to be concerned with WHAT children are doing, just that they have done it. This actually helps create a separation of concerns. Children do something and then the parent responds, rather than the parent needing to monitor everything the child does (which could involve some knowledge of the child implementation)</li></ul><p>Cons</p><ul><li>This does require child elements to be somewhat aware of their parents. This is often something folks try to avoid. However, while the child is aware of the interface it is not aware of the implementation which is an important distinction.</li><li>Registration order matters. If you are going to register your elements after the DOM is parsed you need to make sure you define parents before children. All of the solutions mentioned here have this problem is SOME scenarios.</li><li>Above implementation only works with the immediate parent. While for my use-case this was done on purpose you may want this to work further up the tree. If that is the case you could dispatch bubbling events or use “this.closest(‘some-selector’)”.</li></ul><h4>Conclusion</h4><p>I hope the above has piqued your interest and has your thinking about composing your elements with child elements rather than props. I know that there are valid criticisms of what I am proposing above but the more I start to use it the more I think it is a solid foundation that avoids a couple of potential timing issues. If you want a much larger example, take a look at this<a href="https://github.com/deebloo/go-board"> go board web component</a> that is built with the above technique.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=911122f48d50" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/stream-able-web-components-and-their-parent-child-relationship-911122f48d50">Stream-able Web Components and their parent/child relationship</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React style “context” using custom elements]]></title>
            <link>https://itnext.io/react-style-context-using-custom-elements-74133d7ff683?source=rss-882e20165484------2</link>
            <guid isPermaLink="false">https://medium.com/p/74133d7ff683</guid>
            <category><![CDATA[web-components]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Danny Blue]]></dc:creator>
            <pubDate>Wed, 01 Nov 2023 23:30:11 GMT</pubDate>
            <atom:updated>2024-11-13T17:57:15.544Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EQHqeBB-q8FU8HlSJcskRw.png" /></figure><p>NOTE: To jump straight to the documentation and examples you can view the <a href="https://github.com/joist-framework/joist/tree/main/packages/di#custom-elements">@joist/di README</a>.</p><p>Dependency injection is a concept that allows you to provide given implementations to a given scope. React offers an API called context that lets you do this. If you aren’t familiar with context I recommend reading about it <a href="http://test.com/">here</a>. A short summary from the website reads “Context provides a way to pass data through the component tree without having to pass props down manually at every level.”</p><p>Using a small library called @joist/di we can do something very similar using custom elements. @joist/di is a dependency injection library that works with any JavaScript class. By decorating another class with @injectable(), you can inject singletons.</p><pre>import { injectable, inject, DOMInjector } from &#39;@joist/di&#39;;<br><br>class Debugger {<br>  log(...args: any[]) {<br>    console.log(...args);<br>  }<br>}<br><br>@injectable()<br>class DataService {<br>  #debugger= inject(Debugger);<br>  #data = [0, 1, 2, 3, 4, 5, 6];<br><br>  getData() {<br>    this.#debugger().log(this.#data);<br><br>    return this.#data;<br>  }<br>}<br><br>// We are using DOMInjector here since we will be using custom elements later<br>const app = new DOMInjector();<br>app.attach(document.body);<br><br>const app = new Injector();<br>const data = app.get(DataService);<br><br>const res = data.getData();</pre><p>Since we are using Dependency Injection we also have the ability to provide different implementations for our debugger. We could have a very basic debugger that logs to the console, we could have another that dispatches events into a redux store, or even one that sends data back to out backend services. For our example we will stick with two, the default “noop” debugger, and one that logs to the console.</p><p>Any class decorated with @injectable can have providers defined for it. Those provides will be used by any children and scoped to that injectable.</p><pre>import { injectable } from &quot;@joist/di&quot;;<br><br>// default noop debug service<br>class Debug {<br>  log(...values: any[]) { }<br>}<br><br>// implement debug service using console<br>class ConsoleDebug extends Debug{<br>  log(...values: any[]) {<br>    console.log(...values);<br>  }<br>}<br><br>@injectable({<br>  // define a new implementation of the DebugService<br>  providers: [<br>    { provide: Debug, use: ConsoleDebug }<br>  ]<br>})<br>class DebugCtx extends HTMLElement {}<br><br>customElements.define(&quot;debug-ctx&quot;, DebugCtx);</pre><p>Now we could create multiple context elements for different situations. By default our debugger outputs nothing, when another element is wrapped in a context element it will use the debugger that is defined in that scope.</p><pre>import { injectable, inject } from &#39;@joist/di&#39;;<br><br>@injectable()<br>class MyElement extends HTMLElement {<br>  #debugger = inject(Debug);<br><br>  connectedCallback() {<br>    const debugger = this.#debugger();<br><br>    debugger.log(&#39;MyElement connected!&#39;)    <br>  }<br>}<br><br>customElements.define(&#39;my-element&#39;, MyElement);</pre><pre>&lt;!-- nothing will be logged --&gt;<br>&lt;my-element&gt;&lt;/my-element&gt;<br><br>&lt;debug-ctx&gt;<br>  &lt;!-- logged using ConsoleDebugger --&gt;<br>  &lt;my-element&gt;&lt;/my-element&gt;<br>&lt;/debug-ctx&gt;</pre><p>In fact you can event use @joist/di right along with the React context API!</p><pre>import { Injector, Provider, ProviderToken, Injectable } from &#39;@joist/di&#39;;<br>import React, { PropsWithChildren, createContext, useContext } from &#39;react&#39;;<br><br>// Create context<br>export const InjectorCtx = createContext&lt;Injector | null&gt;(null);<br><br>export function InjectorProvider(props: PropsWithChildren&lt;{ providers: Provider&lt;any&gt;[] }&gt;) {<br>  // create a new injector for each instance of InjectorProvider<br>  const injector = new Injector(props.providers);<br>  const parent = useContext(InjectorCtx);<br><br>  // if there is a parent Ctx assign it to the injector<br>  if (parent) {<br>    injector.setParent(parent);<br>  }<br><br>  return &lt;InjectorCtx.Provider value={injector}&gt;{props.children}&lt;/InjectorCtx.Provider&gt;;<br>}<br><br>export function useInject&lt;T extends Injectable&gt;(token: ProviderToken&lt;T&gt;): T {<br>  const ctx = useContext(InjectorCtx);<br><br>  if (ctx === null) {<br>    throw Error(&#39;useInject cannot be used outside of InjectorProvider&#39;);<br>  }<br><br>  return ctx.get(token);<br>}</pre><p>HTML gives us an out of the box structure for defining a parent/child relationship (it is kind of how it works) and @joist/di is smart enough to know when it is being using in the dom and to look for its parents.</p><p>For a runnable example you can check out the todo list demo in the <a href="https://github.com/joist-framework/joist/blob/main/integration/todo/index.html#L117">joist repository</a>. The ability to use HTML as scoping for your JavaScript code opens a lot of doors. Use it for theming, use it for debugging, even use them to help implement forms. What cool things do you think you could build with context and dependency injection?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74133d7ff683" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/react-style-context-using-custom-elements-74133d7ff683">React style “context” using custom elements</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to ”handle” yourself in Joist]]></title>
            <link>https://itnext.io/how-to-handle-yourself-in-joist-fa4b52b2b085?source=rss-882e20165484------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa4b52b2b085</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Danny Blue]]></dc:creator>
            <pubDate>Wed, 02 Sep 2020 03:56:54 GMT</pubDate>
            <atom:updated>2020-09-02T06:54:33.210Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WTAyDtDZkG73HrgNzH8mng.png" /></figure><p>Not long ago I introduced a new framework called <a href="https://itnext.io/introducing-joist-313f111a428">Joist</a>. As pointed out in that introduction, one of the more unique features of Joist is the concept of “handlers” and because of this I thought it would be worth digging into what handlers are and what you can do with them.</p><p>NOTE: If you haven’t read the introduction I suggest you do so.</p><p>A handler in Joist allows a user to map one or more class methods to an “action” and one or more actions to a single class method. In more plain terms, a single action can trigger one or many methods to be called. Think of it somewhat like an event system.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/307e60a0fc9c9743715ad871cb2e77d6/href">https://medium.com/media/307e60a0fc9c9743715ad871cb2e77d6/href</a></iframe><p>In the simple example above it can be hard to see how this could be useful as it would be much more straight forward to just call the methods directly. To help show how you can benefit from handlers let’s talk about what an action should itself should be. An action name should describe what is happening. For example instead of “increment” we could say something more descriptive like “inc_btn_clicked”. This explains exactly what interaction has happened. If we take this naming approach coupled with the ability for a single method to handle multiple actions our above example might look something like this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7dea146947039945baa98988d8fd85c/href">https://medium.com/media/a7dea146947039945baa98988d8fd85c/href</a></iframe><p>Now our code more explicitly tells us that when the decrement button is clicked OR the increment button is clicked we are going to update the existing count. This helps us see what is going on in our component, we can see what actions occur and in what order. This can be a helpful tool to help with debugging.</p><p>Joist handlers can also match based on a regular expression. For example you might decide that you want to match any action that ends with “btn_clicked”, or in our code below we can create a debug function and watch any and all actions and log them out.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec215a41075e5b9b06f4a4b5978541b8/href">https://medium.com/media/ec215a41075e5b9b06f4a4b5978541b8/href</a></iframe><p>Some of you out there might be starting to think of this as similar to how you would debug an application built with flux or redux, the piece we are missing is seeing how our state is changing, we can see actions flowing in but don’t see our state flowing out.</p><p>There are a couple of ways we could handle viewing updates to our state. We could just listen directly to our injected state object for changes but then we would have to correlate which action caused which state update ourselves. The more straight forward way is to make use of Joist’s onComplete callback. Joist handlers have the ability to return a Promise so Joist knows once all callbacks have completed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc1a1b36902b3767f64c8b82f77dbf05/href">https://medium.com/media/fc1a1b36902b3767f64c8b82f77dbf05/href</a></iframe><p>Using handlers allows us to keep our template code completely isolated from our component code. This lets you define very clear component code without needing to care about what is in the template, your component just needs to listen for actions and set state, it could care less about the presentation layer.</p><p>This has been a brief look into the concept of handlers in Joist. Handlers give us some interesting capabilities, are there any you can think of that I haven’t mentioned here? Let me know and give Joist a spin!</p><p><a href="https://github.com/joist-framework/joist">https://github.com/joist-framework/joist</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa4b52b2b085" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/how-to-handle-yourself-in-joist-fa4b52b2b085">How to ”handle” yourself in Joist</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introducing Joist]]></title>
            <link>https://itnext.io/introducing-joist-313f111a428?source=rss-882e20165484------2</link>
            <guid isPermaLink="false">https://medium.com/p/313f111a428</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Danny Blue]]></dc:creator>
            <pubDate>Thu, 06 Aug 2020 16:29:19 GMT</pubDate>
            <atom:updated>2020-09-21T22:46:23.009Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*rJNZL3mO-lhMvNBiliW7Tw.png" /></figure><p>I’ve done it. I have done the thing that everyone tells you not to do as a developer directly following “don’t build your own cms (which I have also done)”. I built my own framework, <a href="https://github.com/joist-framework/joist">Joist</a>.</p><p>Over the past 2 or so years I have been thinking about how I personally like to write applications and build components and couldn’t find anything that did EXACTLY what I wanted EXACTLY the way I wanted. So i built Joist, a framework that I want to use that I don’t mind if you want to use too :).</p><p>Some of the things I wanted:</p><ul><li>dependency injection</li><li>SMALL</li><li>opinionated state management</li><li>framework agnostic components (WebComponents)</li><li>view layer agnostic (You should be able to swap between no view library, lit-html and lighterhtml whenever you like.)</li></ul><p>In my opinion Joist meets all of my criteria. It is opinionated in some aspects and flexible in others. On it’s own <strong>@joist/component</strong> and <strong>@joist/di</strong> together weigh in at <strong>~2kb</strong> gzipped and <strong>~5kb</strong> with lit-html.</p><h3>Getting Started</h3><p>The easiest way to get started with Joist is by going to <a href="https://webcomponents.dev/new/">webcomponents.dev</a> and using the Joist starter. Webcomponents.dev is a an EXCELLENT site that lets you build and publish components with a variety of libraries. (Seriously even if you don’t care about Joist you should check it out.)</p><p>If you want to build an application you can use Create Snowpack App (CSP).</p><pre>npx create-snowpack-app my-app --template @joist/starter-snowpack</pre><p>This will set you up with a dev server, production builds via <a href="https://rollupjs.org/">rollup</a> and unit testing via <a href="https://github.com/modernweb-dev/web/tree/master/packages/test-runner">web-test-runner</a>.</p><h3>Elements</h3><p>Joist is view library agnostic but comes with built in support for lit-html and is what we will use for all of our examples. Now let’s see what a Joist element looks like.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e2cc778a56dd7339b55afa86bf5bb97/href">https://medium.com/media/0e2cc778a56dd7339b55afa86bf5bb97/href</a></iframe><p>A Joist component is defined by extending the JoistElement base custom element and adding some component metadata. Metadata includes the tag name of the new element, the default state of the element and the render function. A joist render function is passed an object called RenderCtx.</p><h3>Component Styling</h3><p>When you are using shadow dom you can apply styles with the component `styles` property. Joist will leverage <a href="https://developers.google.com/web/updates/2019/02/constructable-stylesheets">Constructable Stylessheets</a> when available but allows renderers to fall back for browsers without support.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/891e5313384e928af53d5937d15160c7/href">https://medium.com/media/891e5313384e928af53d5937d15160c7/href</a></iframe><h3>Dependency Injection (DI)</h3><p>At the heart of Joist is the dependency injector. The dependency injector itself is completely separate from components and is in its own package. Each Joist component has its own injector that inherits from a single global injector. This allows Joist components to construct their own locally scoped services as well as share global singletons. Services decorated with the “service” decorator will be treated as singletons.</p><p>Services can be injected into the constructor of other services via the “inject” decorator.</p><p>Custom elements can inject services with the “get” decorator. This maps a service to a property on any class that implements the InjectorBase interface. <a href="https://webcomponents.dev/edit/VjIipjsrfLWkmQ1eLMrT">You can even use it with other web component libraries like Microsoft’s FASTElement.</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6b2f4c35eb8261d6d5cf1a6141d84cfa/href">https://medium.com/media/6b2f4c35eb8261d6d5cf1a6141d84cfa/href</a></iframe><p>Property based DI with the get decorator is “lazy”, meaning that the service won’t be instantiated until the first time it is requested.</p><h3>State</h3><p>Joist components differentiate between element properties and internal state. Updating internal state will cause the component view to update. This is on purpose in order to make state updates explicit. Any change in state will result in a change in the view. Joist’s component state is accessible via the State service. You can update state with the setValue and patchValue methods and watch for state changes with onChange.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d99f867467b4827552e7402c8c4cbbc/href">https://medium.com/media/6d99f867467b4827552e7402c8c4cbbc/href</a></iframe><p>Component state is updated asynchronously which means you can pass setValue and patchValue a promise that resolves to your new state.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3feda1da95ff2a6d97e837dbdcc5e2a6/href">https://medium.com/media/3feda1da95ff2a6d97e837dbdcc5e2a6/href</a></iframe><h3>Properties</h3><p>Since Joist elements are Custom Elements, properties behave as you would expect for an HTMLElement. Decorating your properties with the “property” decorator which will cause your elements onPropChanges method to be called with a list of PropChangs whenever that property is updated. You can use this feedback to determine when your element should update.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4522e31fb8aa8949b19f8f78d8427e67/href">https://medium.com/media/4522e31fb8aa8949b19f8f78d8427e67/href</a></iframe><p>Properties also have a hook for runtime validation. The property decorator can accept 1 or many validation functions that will be run when that property is set. This is particularly helpful if you are distributing components. A validator function either return null, meaning there is no error, or an error message.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a439e319595910c6311b2919cd4108e/href">https://medium.com/media/6a439e319595910c6311b2919cd4108e/href</a></iframe><h3>Handlers</h3><p>Handlers are one of the more unique features of Joist. Handlers are way to map an “action” to corresponding methods. Multiple methods can be mapped to a single action. Multiple actions can be mapped to a single method. Handlers can can also match action based on a regular expression. The general flow is <strong>event -&gt; handler -&gt; state change</strong>. <a href="https://itnext.io/how-to-handle-yourself-in-joist-fa4b52b2b085">Check out this article for a more in depth look into handlers.</a></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82802cbac50cc7e312024bcb96560aee/href">https://medium.com/media/82802cbac50cc7e312024bcb96560aee/href</a></iframe><h3>Closing Thoughts</h3><p>That is a quick and dirty overview of Joist. Joist is built to be opinionated but can be used <a href="https://github.com/joist-framework/joist/tree/master/packages/component#use-with-vanilla-custom-elements">à la carte</a>. The package that I didn’t cover here is <a href="https://github.com/joist-framework/joist/tree/master/packages/router">@joist/router</a> which is stable but still a work in progress. Joist is a project I have been playing around and thinking about for quite a while and I think I am pretty happy with the result! Give it a shot, let me know what you think.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=313f111a428" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/introducing-joist-313f111a428">Introducing Joist</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn Dependency Injection By Building an Injector]]></title>
            <link>https://itnext.io/learn-dependency-injection-by-building-an-injector-fb48408af6a?source=rss-882e20165484------2</link>
            <guid isPermaLink="false">https://medium.com/p/fb48408af6a</guid>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Danny Blue]]></dc:creator>
            <pubDate>Wed, 20 Mar 2019 15:13:27 GMT</pubDate>
            <atom:updated>2019-08-11T21:19:55.007Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KXZvJi2c-PhIxo_rZflZxA.png" /></figure><p>If you have built anything with Angular you have no doubt had some experience with Dependency Injection (DI), but not everyone uses Angular and even folks using Angular may not really understand what DI is doing. To really explore this we can build out our DI container in~20 lines of TypeScript (You can use vanilla JavaScript but I feel the type annotations help).</p><p>First, let’s start with a simple definition of DI. From <a href="https://en.wikipedia.org/wiki/Dependency_injection">Wikipedia</a> “In <a href="https://en.wikipedia.org/wiki/Software_engineering">software engineering</a>, <strong>dependency injection</strong> is a technique whereby one object supplies the dependencies of another object.” While that sounds nice let’s look at a concrete example.</p><pre>class HttpService {<br>  get(url: string) {...}<br>  post(url: string) {...}<br>}</pre><pre>class UserService {<br>  constructor(private http: HttpService) {}</pre><pre>  login(email: string, password: string) {<br>    return this.http.post(&#39;/login&#39;, { email, password})<br>  }<br>}</pre><pre>const userService = new UserService(new HttpService())</pre><p>In the above example we don’t want our UserService to care about how to make an http request, we want it to care about how to login. While the example above meets our requirements now it could be become cumbersome as we get more dependencies. We don’t want to care how you create an HttpService, we want to say “HEY I NEED TO MAKE HTTP REQUESTS GIVE ME THE HTTP SERVICE!!!!” This is when an injection container becomes useful. The previous example using one of these mystery containers might look something like this.</p><pre>class HttpService { ... }</pre><pre>class UserService { ... }</pre><pre>// this is the thing we are going to build<br>const injector = new Injector();</pre><pre>const userService = injector.get(UserService);</pre><p>OK cool, so we want our injector to do a couple things:</p><ol><li>It should create a new instance of the class it is given.</li><li>It should create new instances of the dependencies of the given class.</li><li>It should return SINGLETON objects. This means that if an instance has previously been created it will return that instance.</li></ol><h4>Step 1–2: Creating instance and dependencies</h4><p>First we need to create a new instance. Before continuing, stop and think about what pieces of information we need in order to do this dynamically… thought about it? We need to know WHAT the dependencies are. To make things explicit we are going to statically declare the dependencies on our class.</p><pre>class HttpService {}</pre><pre>class AuthService {<br>  static deps = [HttpService];<br>  ...<br>}</pre><p>Now we can have everything we need to create new instances and can create our first version of our Injector!</p><pre>// This type defines a &quot;Provider&quot; <br>// as a class with a static &quot;deps&quot; property<br>type Provider&lt;T&gt; = {<br>  deps: Provider&lt;any&gt;[];</pre><pre>  new (...args: any[]): T;<br>};</pre><pre>class Injector {<br>  get&lt;T&gt;(P: Provider&lt;T&gt;): T {<br>    return new P(...P.deps.map(dep =&gt; this.get(dep)));<br>  }<br>}</pre><p>And that is it! What is happening is we create a new instance of “P” and we recursively call “Injector.get” to get an instance of each dependency, neat! At the moment each time “Injector.get” is called new instances are created.</p><h4>Step 3: Caching results and returning singletons</h4><p>Now that we are successfully creating new instances of our services and our services dependencies, we need to remember them somehow so they can be returned later. We need a cache!</p><pre>type Provider&lt;T&gt; = { ... };</pre><pre>class Injector {<br>  // singleton cache<br>  private cache = new WeakMap&lt;Provider&lt;any&gt;, any&gt;();</pre><pre>  get&lt;T&gt;(P: Provider&lt;T&gt;): T {<br>    // if provided is in cache return it<br>    if (this.cache.has(P)) {<br>      return this.cache.get(P);<br>    }</pre><pre>    // if no existing instance create a new one<br>    const instance = new P(...P.deps.map(dep =&gt; this.get(dep)));<br>    <br>    // then cache the resulting instance<br>    this.cache.set(P, instance);<br>    <br>    return instance<br>  }<br>}</pre><p>Now that we have our cache we can always return a singleton which means that our objects can now hold state if we wish.</p><p>Now let’s look at a more complicated example of what we can do with the above injector.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fstackblitz.com%2Fedit%2Fdi-example%3Fembed%3D1%26file%3Dindex.ts%26view%3Deditor&amp;url=https%3A%2F%2Fstackblitz.com%2Fedit%2Fdi-example%3Fembed%3D1%26file%3Dindex.ts%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/6534a613b9f0fc2a023d4893ba31e5d7/href">https://medium.com/media/6534a613b9f0fc2a023d4893ba31e5d7/href</a></iframe><p>And that is it! Hopefully this simple example of a DI container helps you understand what DI is doing and roughly how it works.</p><p>What other features could you add to this Injector implementation? What if an Injector could have a parent? What would it look like to override a provider? Have a hack and let me know what you come up with!</p><p><a href="https://github.com/deebloo/ts-kit/tree/master/packages/di">If you want to see a more complicated implementation take a look at here.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fb48408af6a" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/learn-dependency-injection-by-building-an-injector-fb48408af6a">Learn Dependency Injection By Building an Injector</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using Angular’s Router to manage state]]></title>
            <link>https://itnext.io/using-angulars-router-to-manage-state-14b1142a2ffb?source=rss-882e20165484------2</link>
            <guid isPermaLink="false">https://medium.com/p/14b1142a2ffb</guid>
            <category><![CDATA[rxjs]]></category>
            <category><![CDATA[itnext]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular]]></category>
            <dc:creator><![CDATA[Danny Blue]]></dc:creator>
            <pubDate>Wed, 24 Jan 2018 13:02:32 GMT</pubDate>
            <atom:updated>2018-01-25T14:59:22.277Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nX9K-hqQ0U1JiByqYJsT6g.png" /></figure><p><a href="https://www.linkedin.com/cws/share?url=https%3A%2F%2Fitnext.io%2Fusing-angulars-router-to-manage-state-14b1142a2ffb"><em>Click here to share this article on LinkedIn »</em></a></p><p>Ah the url, an often overlooked place to hold state in modern apps but one that is oh so powerful. Have you ever gone to a website, searched, set all your filters, refreshed and then it all goes away? This is a prime example of why well designed router/url state is important. While this article is about Angular specifically the main idea of storing state in the URL is applicable to all frameworks/apps.</p><p>Let’s take a look at an example URL for a search page. The requirements for our url is that it needs to say which page needs to be navigated to, hold the value the user searched for and hold several search filters.</p><pre>/products?search=playstation?department=electronics&amp;priceLimit=100</pre><p>The above url tell’s our application several things about it’s state so let’s break it down.</p><pre>products - The page we are viewing</pre><pre>search=playstation - The search value</pre><pre>department=electronics - the department filter</pre><pre>priceLimit=100 - the price limit filter</pre><p>Since Angular’s router is reactive it becomes very simple to use these values as the source for our search page.</p><pre>import { Component } from &#39;@anguar/core&#39;;<br>import { ActivatedRoute } from &#39;@angular/router&#39;;<br>import { Observable } from &#39;rxjs/Observable&#39;;<br>import { switchMap } from &#39;rxjs/operators&#39;;</pre><pre>import { SearchService } from &#39;./search.service&#39;;</pre><pre>export interface SearchParams {<br>  department: string;<br>  priceLimit: string;<br>  search: string;<br>}</pre><pre>@Component({<br>  template: `<br>    {{searchParams | async | json}} </pre><pre>    {{results | async | json}}<br>  `<br>})<br>class MyComponent {<br>  searchParams: Observable&lt;SearchParams&gt; = this.route.queryParams</pre><pre>  results = this.searchParams.pipe(<br>    switchMap(params =&gt; this.ss.findProducts(params))<br>  );</pre><pre>  constructor(<br>    private ss: SearchService, <br>    private route: ActivatedRoute<br>  ) {}</pre><pre>  updateSearch(params: Partial&lt;SearchParams&gt;) {<br>    this.router.navigate([&#39;.&#39;], {<br>      queryParameters: params, <br>      queryParamsHandling: &#39;merge&#39;<br>    })<br>  }<br>}</pre><p>Now if we look into the component definition above we notice 3 things.</p><ol><li>The query parameters are an Observable, meaning that whenever a query parameter changes our subscribers (in this case our template via the “async” pipe) will be notified</li><li>We can use the RxJs “switchMap” operator to trigger a new search whenever one of those parameters changes.</li><li>All we have to do to update our view is change one of those parameters. (see the “updateSearch” method in the component. One can imagine it being called when someone selects a checkbox)</li></ol><p>Following this pattern there is no need to manage local state manually or use a global app store, the URL IS the state of the view and will tell us when things need to change.</p><p>Now your route isn’t an ideal place to store EVERYTHING so let’s look at some example of what it is and isn’t good for.</p><p>GOOD:</p><ul><li>Filters: Think an Amazon page or JIRA.</li><li>Anything that needs to be easily sharable by a user: Filters are again a good example or maintaing the correct “page” in a multi page table</li><li>Any state that needs to be maintained on refresh: Filters, Page, current tab</li><li>Simple Values: strings, numbers, booleans or arrays of these values which would look like this:</li></ul><pre>products?list=first?list=second&amp;list=third</pre><p>BAD:</p><ul><li>Complex values: The url is great for storing simple primitives or arrays of primitives, (An array of primitives is represented by adding a query parameter with the same name multiple tiles) but bad at storing more complex structures like…</li><li>Objects: you may be tempted at times to just JSON.stringify an object and throw it in a query param, please don’t… please?</li></ul><p>In closing think about yourself as the user, if there is a chance you would be annoyed having to navigate back to the correct tab or reselect filter or search parameters there is a greater then 0 change your users will too.</p><p>If you have any other interesting use cases or implementations using reactive query or route parameters let me know in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14b1142a2ffb" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/using-angulars-router-to-manage-state-14b1142a2ffb">Using Angular’s Router to manage state</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Help Keep Angular Forms Type-Safe]]></title>
            <link>https://itnext.io/help-keep-angular-forms-type-safe-ca35f7b2edf8?source=rss-882e20165484------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca35f7b2edf8</guid>
            <category><![CDATA[itnext]]></category>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[type-safety]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Danny Blue]]></dc:creator>
            <pubDate>Tue, 23 Jan 2018 13:03:56 GMT</pubDate>
            <atom:updated>2024-07-24T20:18:07.999Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aTCN2ctKNoZupUCMP0hQuw.png" /></figure><p><strong>NOTE: This article is not longer relevant with the following being merged into the forms module. </strong><a href="https://github.com/angular/angular/discussions/44513"><strong>https://github.com/angular/angular/discussions/44513</strong></a></p><p><a href="https://www.linkedin.com/cws/share?url=https%3A%2F%2Fitnext.io%2Fhelp-keep-angular-forms-type-safe-ca35f7b2edf8"><em>Click here to share this article on LinkedIn »</em></a></p><p>NOTE”</p><p>Angular Reactive Forms are awesome and very powerful but in my opinion they have one GLARING fault, and that is that they are not type-safe. Let’s look at an example to demonstrate. (We will be using FormBuilder for all examples.)</p><pre>class MyComponent {<br>  myForm: FormGroup = this.fb.group({<br>    firstName: [&#39;&#39;],<br>    lastName: [&#39;&#39;]<br>    email: [&#39;&#39;]<br>  });<br>  constructor(private fb: FormBuilder) {}<br>  onSubmit() {<br>    console.log(this.myForm.value);<br>  }<br>}</pre><p>Above we can see a simple FormGroup model defined with 3 properties, but if we were to hover over the “value” property in our IDE we would see the type is “any”! In this small example it might not be a big deal, but once we get into larger, more dynamic forms it can cause some hard to track down bugs.</p><p>While my preferred solution would be for AbstractControl to be a generic and allow something like this: (there is actually an issue for this <a href="https://github.com/angular/angular/issues/13721">here</a> so fingers crossed.)</p><pre>myForm: FormGroup = this.fb.group&lt;MyFormModel&gt;({<br>  firstName: [&#39;&#39;],<br>  lastName: [&#39;&#39;]<br>  email: [&#39;&#39;]<br>});</pre><p>We can work around this limitation and at least make our type-SAFEISH if not actually type-safe. Our solution should meet 3 criteria:</p><ol><li>When we CREATE a form we should KNOW the shape of the object the form expects.</li><li>When we UPDATE a form we KNOW the properties that are available to be updated.</li><li>When we get the value of our form we KNOW it’s shape.</li></ol><p>So how do we get started? Let’s take it one step at a time.</p><p>First we know that we want to define a model so let’s go ahead and do just that.</p><pre>interface MyFormModel {<br>  firstName: string;<br>  lastName: string;<br>  email: string;<br>}</pre><p>We want to tell our form that it has three properties that are string. Next we need a method that returns a form and that accepts our model as an argument.</p><pre>private createForm(model: MyFormModel): FormGroup {<br>  return this.fb.group(model);<br>}</pre><p>Now when we call “createForm” the compiler will tell us whether or not we have all of the properties. Next is a method for updating. (Partial is built in to TypeScript and makes every property of its argument optional)</p><pre>private updateForm(model: Partial&lt;MyFormModel&gt;): void {<br>  this.myForm.patchValue(model)<br>}</pre><p>And finally, a property for looking at the value of the form. Here we can use casting to tell the compiler that the value of “myForm” is MyFormModel</p><pre>get formValue() {<br>  return this.myForm.value as MyFormModel;<br>}</pre><p>Put it all together and we get…</p><pre>import { Component } from &#39;@angular/core&#39;;<br>import { FormGroup, FormBuilder } from &#39;@angular/forms&#39;;<br><br>interface MyFormModel {<br>  firstName: string;<br>  lastName: string;<br>  email: string;<br>}<br><br>@Component(...)<br>export class MyComponent {<br>  myForm: FormGroup = this.createForm({<br>    firstName: &#39;&#39;,<br>    lastName: &#39;&#39;,<br>    email: &#39;&#39;<br>  });<br>  get formValue() {<br>    return this.myForm.value as MyFormModel;<br>  }<br><br>  constructor(private fb: FormBuilder) {}<br>  <br>  onSubmit() {<br>    console.log(this.myForm.value);<br>  }<br><br>  private createForm(model: MyFormModel): FormGroup {<br>    return this.fb.group(model);<br>  }<br><br>  private updateForm(model: Partial&lt;MyFormModel&gt;): void {<br>    this.myForm.patchValue(model)<br>  }<br>}</pre><p>And that’s all! Now we can be a bit more confident when updating our forms and it will also now be much safer when we have to CHANGE anything about that form.</p><p>Thanks for reading! If you have any other idea on how to be safer when working for Reactive Forms let me know I would love to see them.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca35f7b2edf8" width="1" height="1" alt=""><hr><p><a href="https://itnext.io/help-keep-angular-forms-type-safe-ca35f7b2edf8">Help Keep Angular Forms Type-Safe</a> was originally published in <a href="https://itnext.io/">ITNEXT</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Custom Element Inter-op with Angular]]></title>
            <link>https://deebloo.medium.com/custom-element-inter-op-with-angular-2-ed75f013a9ba?source=rss-882e20165484------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed75f013a9ba</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[web-components]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Danny Blue]]></dc:creator>
            <pubDate>Fri, 01 Jul 2016 02:52:08 GMT</pubDate>
            <atom:updated>2019-04-11T00:41:47.359Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*PgppNaI9YmbRFz2mIkIkOQ.png" /></figure><p>NOTE: This article and the examples have been updated to use the custom elements v1. To see the differences between v0 and v1 checkout this <a href="https://github.com/WebReflection/document-register-element">readme</a>.</p><p>The web development community moves at lightning speed, this often means porting your project to the newest framework every couple of years. This could mean porting Angular 1 directives to React components and maybe now React components to Angular components. I don’t know about most of you, but I am tired of rewriting custom drop-down menus.</p><p>And now, web components enter the ring. Web components are made up of 4 separate specs, custom elements, shadow DOM, HTML imports, and the template tag. For the purposes of this article we will focus specifically on custom elements.</p><p>In reality, you could write an entire application with custom elements and some sort of state manager (Redux, etc), but there are many who enjoy the out of the box functionality that comes with frameworks. So what we need now, is the ability to easily drop our custom elements into our existing applications.</p><p>Our focus here (SURPRISE) will be to create our own custom element and use it in our shiny new Angular application. Since we are using Angular as our inter-op example we will use typescript. If you want to see more about Angular check out the <a href="https://angular.io/docs/ts/latest/quickstart.html">quick start</a>, and for more information on Typescript check out the <a href="https://www.typescriptlang.org/docs/tutorial.html">site</a>.</p><p>First our basic “Hello World” Angular application. First we create a simple root component, a simple root module, and then bootstrap that module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72fe12e28e53f658045f8e0d69d4bdd8/href">https://medium.com/media/72fe12e28e53f658045f8e0d69d4bdd8/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e93bbde40c344352d33dfbfecbf77ffd/href">https://medium.com/media/e93bbde40c344352d33dfbfecbf77ffd/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/633553ec1f56f527c75864131b732733/href">https://medium.com/media/633553ec1f56f527c75864131b732733/href</a></iframe><p>Nothing fancy here, just the basic setup. Now it is time for the good stuff. Now it is time for our custom element.</p><p>Since we are using typescript for our Angular application we will use the same for our custom element as well. You could also use ES6 or ES5 but to keep things consistent I am deciding to go with typescript. Creating the custom element is a bit more involved but nothing scary. The inline comments should provide clarity into what is happening.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4c9bd99c45d35f303a4d0454dc7e085a/href">https://medium.com/media/4c9bd99c45d35f303a4d0454dc7e085a/href</a></iframe><p>The most important parts of our custom element for inter-op are our property getters/setters and our custom event (logoClicked). If those two things didn’t play nice, inter-op would be a nightmare. This custom element has a very simple render function and just re-renders the whole thing when our src property changes, but we could be clever and only update the bits that changed if we so wished.</p><p>Now we need to get our custom element into our application. We do that by importing it the same way we would any other external dependency. Now we can use our custom &lt;app-logo&gt; element anywhere in our app.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e92b9742a75b534450620be2a7c48ef5/href">https://medium.com/media/e92b9742a75b534450620be2a7c48ef5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51cb746484a80768457f637ade6c103d/href">https://medium.com/media/51cb746484a80768457f637ade6c103d/href</a></iframe><p>You will notice if you run your code now you will get an error from angular. Thankfully, Angular tells us that it it does not know about the property “src” since it does not belong to the element “app-logo”. To suppress this message we have to add one final thing to our app.module.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e2a2a28665c5a3b8a80223467e5c665/href">https://medium.com/media/0e2a2a28665c5a3b8a80223467e5c665/href</a></iframe><p>Adding the CUSTOM_ELEMENT_SCHEMA to this module will now allow us to use our custom element within the module.</p><p>As you can see there is nothing that differentiates this custom element from any other native element or Angular component. There is really no integration work we need to do, it is now plug and play.</p><p>You can check out a full working example <a href="https://plnkr.co/edit/xJ40XK?p=preview">here</a>.</p><p>THATS IT! Angular lets us use its standard syntax for interacting with our custom element. Now we have a custom UI component that doesn’t depend on Angular at all. Custom elements afford us the ability to be framework agnostic and leverage the web platform we all know and love.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed75f013a9ba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make multithreading easier with Inline Web Workers]]></title>
            <link>https://deebloo.medium.com/make-multithreading-easier-with-inline-web-workers-a58723428a42?source=rss-882e20165484------2</link>
            <guid isPermaLink="false">https://medium.com/p/a58723428a42</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[webworker]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Danny Blue]]></dc:creator>
            <pubDate>Sat, 04 Jun 2016 19:02:27 GMT</pubDate>
            <atom:updated>2018-01-24T18:50:55.104Z</atom:updated>
            <content:encoded><![CDATA[<p>Web Workers are awesome, and yet somehow they are not nearly as widely used despite their pretty good browser support (IE10 and up). One reason for that is maybe they don’t find into your normal development flow and build setup.</p><p>First up a quick refresher. A web worker is a new OS level thread that is spun up by your browser. This allows the developer to run code without blocking the main UI thread. You communicate with the worker via the post message api. For information on web workers you can view it <a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Using_web_workers">here</a>.</p><p>We can use web workers to prevent things like below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*WlMXK3rs_scqKTRV41au7g.jpeg" /></figure><p>Now let’s take a look at a standard web worker.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/85ace7c4312aaea1df0c26621a81930f/href">https://medium.com/media/85ace7c4312aaea1df0c26621a81930f/href</a></iframe><p>Not bad right? We can now offload any logic we want to a separate thread and keep the UI thread unblocked. COOL! But, maybe maintaining these separate worker files is a pain or just doesn’t fit with how we are writing out code. Wouldn’t it be nice if you could just do this?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f6ba2d08841ebd448442ccfb8e5b7d3/href">https://medium.com/media/7f6ba2d08841ebd448442ccfb8e5b7d3/href</a></iframe><p>Enter inline web workers! Inline web workers allow you to create a web worker from a function that you give it. To get inline workers to work we have to rely on two other technologies, blobs and object urls. Let’s take a look at the createWorker function and see what is in its guts.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/72f2236d2f33b299c405264a4494ec39/href">https://medium.com/media/72f2236d2f33b299c405264a4494ec39/href</a></iframe><p>Thats it! A three line function will let you spin up web workers with no need to maintain separate files, but let’s dissect it and find out what it means.</p><pre>var blob = new Blob([&#39;self.onmessage = &#39;], fn.toString()], { type: &#39;text/javascript&#39;});</pre><p>This line create a new Blob of data that we are telling it is javascript. You can read up on blobs <a href="https://developer.mozilla.org/en-US/docs/Web/API/Blob">here</a>.</p><pre>var url = URL.createObjectURL(blob);</pre><p>Now we still need a url for the worker to use. Can get one dynamically by using the URL.createObjectUrl method. We can pass our freshly minted blob into it and it will give use a url. Now we can use our new object url to create a web worker and we are off to the races.</p><p>Now that we can see how easy it is to create this helper function we can go off and add whatever other abstractions we would like, Even something using promises like so.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df103fcbc39a940bc7bd9e13703f3776/href">https://medium.com/media/df103fcbc39a940bc7bd9e13703f3776/href</a></iframe><p>If you want to see the source code for that you can view it <a href="https://github.com/deebloo/worker">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a58723428a42" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>