<?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 Boolean Julian Jәlfs on Medium]]></title>
        <description><![CDATA[Stories by Boolean Julian Jәlfs on Medium]]></description>
        <link>https://medium.com/@julianjelfs_61852?source=rss-6555944dfe7f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*Q9f3fvuzA8XpITHz.jpeg</url>
            <title>Stories by Boolean Julian Jәlfs on Medium</title>
            <link>https://medium.com/@julianjelfs_61852?source=rss-6555944dfe7f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:02:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@julianjelfs_61852/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[Render props for Elm]]></title>
            <link>https://medium.com/hackernoon/render-props-for-elm-d5547efd66f5?source=rss-6555944dfe7f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d5547efd66f5</guid>
            <category><![CDATA[elm]]></category>
            <dc:creator><![CDATA[Boolean Julian Jәlfs]]></dc:creator>
            <pubDate>Thu, 21 Feb 2019 19:17:17 GMT</pubDate>
            <atom:updated>2019-02-27T11:44:29.001Z</atom:updated>
            <content:encoded><![CDATA[<h4>Well, something like that any way.</h4><p>This is a common UI pattern that is a bit difficult to achieve in Elm. Something like render props from the React world or <em>transclusion</em> if you have escaped from the angular world.</p><p>The idea is that you would like to create a generic component to provide perhaps some wrapper UI and a little bit of state management and then re-use that component but inject your own view (render prop) into it. Good examples of when you might reach for this technique would be a modal or a tab strip. In these cases you don’t want to rewrite the markup and logic that are generic each time. A modal has a header and a footer and you need to track whether it is open or closed etc, but mostly what you care about when you <em>use </em>it is the content for your particular use case.</p><h3>So what’s the problem?</h3><p>It’s in the types. Let’s try to do it and we will see why it doesn’t immediately work. For the sake of simplicity let’s say that my generic component will basically just be a div and that I would like to be able to render my custom container component but inject custom UI into it. My div will have a header that changes colour when you click it (that’s the state that it tracks internally that I want to abstract away).</p><h3>Let’s try it</h3><p>Our ColourClicker component will have the usual Elm lifecycle since it needs to track this little bit of internal state and it might look something like this initially:</p><pre>type alias Model =<br>    { colour : String }</pre><pre>type Msg<br>    = ToggleColour</pre><pre>init : Model<br>init =<br>    { colour = &quot;blue&quot; }</pre><pre>update : Msg -&gt; Model -&gt; Model<br>update msg model =<br>    case msg of<br>        ToggleColour -&gt;<br>            toggleColour model</pre><pre>toggleColour : Model -&gt; Model<br>toggleColour model =<br>    case model.colour of<br>        &quot;blue&quot; -&gt;<br>            { model | colour = &quot;red&quot; }<br>        _ -&gt;<br>            { model | colour = &quot;blue&quot; }</pre><pre>view : Model -&gt; List (Html Msg) -&gt; Html Msg<br>view model content =<br>    div<br>        [ class &quot;colour-clicker&quot; ]<br>        [ h1<br>            [ onClick ToggleColour<br>            , style &quot;background&quot; model.colour<br>            ]<br>            [ text &quot;This is the magical header&quot; ]<br>        , div []<br>            content<br>        ]</pre><p>Hopefully this doesn’t need too much explanation. The view function simply allows us to inject content from the consuming code.</p><p>The code that uses this component might look a bit like this:</p><pre>import ColourClicker as C</pre><pre>type alias Model =<br>    { colourClicker : C.Model }</pre><pre>init : ( Model, Cmd Msg )<br>init =<br>    ( { colourClicker = C.init }, Cmd.none )</pre><pre>type Msg<br>    = ColourClickerMsg C.Msg</pre><pre>update : Msg -&gt; Model -&gt; ( Model, Cmd Msg )<br>update msg model =<br>    case msg of<br>        ColourClickerMsg subMsg -&gt;<br>            let<br>                subModel =<br>                    C.update subMsg model.colourClicker<br>            in<br>            ( { model | colourClicker = subModel }, Cmd.none )</pre><pre>view : Model -&gt; Html Msg<br>view model =<br>    div [ class &quot;demo&quot; ]<br>        [ h1 [] [ text &quot;Demo of render props technique for Elm&quot; ]<br>        , Html.map ColourClickerMsg &lt;|<br>            C.view model.colourClicker<br>                [ div []<br>                    [ text &quot;This is the content of the colour clicker provided by the parent&quot; ]<br>                ]<br>        ]</pre><p>Then end result looks like this and works fine:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/527/1*-y8ifPQ-4pxsimjYTbbf0A.png" /></figure><h3>New feature request</h3><p>Now suppose that I want the content that I inject to contain a button and I want to handle the clicking of that button in my parent component. Like this:</p><pre>type Msg<br>    = ColourClickerMsg C.Msg<br>    | ButtonClicked</pre><pre>update : Msg -&gt; Model -&gt; ( Model, Cmd Msg )<br>update msg model =<br>    case msg of<br>        ...</pre><pre>        ButtonClicked -&gt;<br>            let<br>                _ =<br>                    Debug.log &quot;Button Clicked!&quot; ()<br>            in<br>            ( model, Cmd.none )</pre><pre>view : Model -&gt; Html Msg<br>view model =<br>    div [ class &quot;demo&quot; ]<br>        [ h1 [] [ text &quot;Demo of render props technique for Elm&quot; ]<br>        , Html.map ColourClickerMsg &lt;|<br>            C.view model.colourClicker<br>                [ div []<br>                    [ text &quot;Now we need to add a button&quot;<br>                    , button [ onClick ButtonClicked ] [ text &quot;Click me!&quot; ]<br>                    ]<br>                ]<br>        ]</pre><p>This is a reasonable thing to want to do. We don’t want the ColourClicker component itself to handle this button click because the logic belongs in the calling component. The ColourClicker should only be responsible for its own state (which is the colour of its header). But we have a problem. Our ColourClicker’s view function expects its content to be of type Html ColourClicker.Msg but we are now trying to pass in Html Parent.Msg so the types do not line up and the compiler (rightly) complains.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*59le0Ff0mpsfr5JLxS8-4g.png" /></figure><h3>So what can we do?</h3><p>Let’s follow the types. Firstly, we must make the ColourClicker’s view function accept content with a polymorphic type like this:</p><pre>view : Model -&gt; List (Html parent) -&gt; Html Msg</pre><p>In this signature “parent” is a type parameter to indicate that we do not know what type this Html will have. This gets rid of the previous compiler error but replaces it with a new one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*BJl01dvvQvdQTBWZutD3zA.png" /></figure><p>The issue now is that our ColourPicker’s view is trying to embed Html parent within a block of Html ColourPicker.Msg which is not allowed. So it is clear that we need to somehow map the Html that has been passed in to coerce it to the right type.</p><p>To do this we need to create a new Msg type within the ColourClicker to which to map the parent Msg type, create a function to perform the mapping and call that function when we write out the content:</p><pre>type Msg parent<br>    = ToggleColour<br>    | Parent parent</pre><pre>wrap : Html parent -&gt; Html (Msg parent)<br>wrap =<br>    Html.map Parent</pre><pre>view : Model -&gt; List (Html parent) -&gt; Html (Msg parent)<br>view model content =<br>    div<br>        [ class &quot;colour-clicker&quot; ]<br>        [ h1<br>            [ onClick ToggleColour<br>            , style &quot;background&quot; model.colour<br>            ]<br>            [ text &quot;This is the magical header&quot; ]<br>        , div []<br>            (List.map wrap content)<br>        ]</pre><p>What we have done is to <em>parameterise</em> our own Msg type with the polymorphic parent type such that we can create an instance of our Msg type that <em>contains </em>the parent msg. Note that all of this is transparent to the calling code and introduces no further complexity. This makes the types line up, but isn’t it just a trick? What happens to our update function? It needs to change as follows:</p><pre>update : Msg parent -&gt; Model -&gt; ( Model, Cmd parent )<br>update msg model =<br>    case msg of<br>        ToggleColour -&gt;<br>            ( toggleColour model, Cmd.none )</pre><pre>        Parent p -&gt;<br>            ( model, Task.perform identity (Task.succeed p) )</pre><p>First we need to change the return type to allow us to return a Cmd parent. This is unusual — ordinarily it would be Cmd Msg. We could do that <em>as well</em> if we needed to, but in this case we don’t. Remember there is nothing magical about the update function, it’s just a function — we can do what we like. In the branch of the case statement that handles the new Parent parent message type we simply convert that message into a Cmd using the Task api and return it to the caller.</p><p>The final change required then is to the parent’s update function to handle this new return type correctly. This now looks like this:</p><pre>case msg of<br>   ColourClickerMsg subMsg -&gt;<br>       let<br>           ( subModel, subCmd ) =<br>               C.update subMsg model.colourClicker<br>       in<br>       ( { model | colourClicker = subModel }, subCmd )</pre><p>The subCmd that comes out of the update function is already the right type to just return directly from the parent’s update function. It will ultimately get fed back into the update function as the ButtonClicked msg.</p><p>Everything now compiles! We have really nice idiomatic syntax and we are able to naturally handle the button click at the parent level without the ColourClicker component ever knowing anything about it. We can now reuse the ColourClicker component much more effectively.</p><p>I’d love to hear other approaches to this problem because it took me a while to figure this out and it seems like such a common requirement.</p><p>The code for this example can be found <a href="https://github.com/julianjelfs/elm-render-props">here</a>. Hope this is useful for someone.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d5547efd66f5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/render-props-for-elm-d5547efd66f5">Render props for Elm</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The importance of state ownership in Elm]]></title>
            <link>https://medium.com/hackernoon/the-importance-of-state-ownership-in-elm-72f711ceb244?source=rss-6555944dfe7f------2</link>
            <guid isPermaLink="false">https://medium.com/p/72f711ceb244</guid>
            <category><![CDATA[elm]]></category>
            <dc:creator><![CDATA[Boolean Julian Jәlfs]]></dc:creator>
            <pubDate>Fri, 16 Jun 2017 09:49:57 GMT</pubDate>
            <atom:updated>2017-09-29T08:10:44.291Z</atom:updated>
            <content:encoded><![CDATA[<p>Disclosure — I don’t have all the answers to the problems I am posing here — as ever, there is more than one way!</p><p>Elm manages state using a the single state atom pattern that will be familiar to users of React with redux. The state is initialised and then “modified” in the update function as actions occur. The state is typically passed into the view function to be used in building the UI.</p><p>So far so good, but The Elm Architecture is also fractal in nature. This means that it is typical to compose multiple instance of this patterns together in a tree. This usually means that our state becomes hierarchical too.</p><p>For example in a typical SPA we might have a structure like this:</p><pre>RootComponent<br>    PageOne<br>    PageTwo<br>    PageThree</pre><p>This represents the whole App and then components for each page (related to each route in the app). In this situation it is typical to create a top level Model that looks something like this:</p><pre>type alias Root =<br>    { pageOne: PageOne.Model<br>    , pageTwo: PageTwo.Model <br>    , pageThree: PageThree.Model<br>    }</pre><p>And this structure might be initialiased like this:</p><pre>initialiase: Model <br>initialise =<br>    { pageOne = PageOne.initialise<br>    , pageTwo = PageTwo.initialise<br>    , pageThree = PageThree.initialise<br>    }</pre><p>This is a really useful pattern because it enables us to hide the structure and initialisation logic of the page level Models within the page components.</p><p>But who <em>owns </em>this data? And what does that mean? I will define ownership as follows: a component owns data, if that data is updated solely in the components update function. So the RootComponent’s update function might look like this:</p><pre>update: Msg -&gt; Model -&gt; (Model, Cmd Msg)<br>update msg model =<br>    case msg of<br>        PageOneMsg sub -&gt;<br>            let<br>                (subModel, subCmd) =<br>                    PageOne.update sub model.pageOne<br>            in<br>                ( { model | pageOne = subModel }<br>                , Cmd.map PageOneMsg subCmd )<br>    ...</pre><p>We recognise this as pure boilerplate i.e. we are simply delegating to the PageOne component’s update function and we know that it is responsible for modifying its model in response to the action.</p><p>But what if it’s not that simple (and it never is)? Let’s say that we have the concept of a user and this is generally a root level concern. This may change our RootComponent’s Model to something like this.</p><pre>type alias Root =<br>    { <strong>user: User</strong><br>    , pageOne: PageOne.Model<br>    , pageTwo: PageTwo.Model <br>    , pageThree: PageThree.Model<br>    }</pre><p>And it would be quite typical for us to want to access information about the user at all levels of the app. So how do we achieve this? PageOne’s view function is passed a PageOne.Model so it does not have access to the RootComponent.Model’s user property. Our natural inclination is to push the user property into the PageOne.Model as well.</p><pre>initialiase: <strong>User </strong>-&gt; Model <br>initialise <strong>user </strong>=<br>    { pageOne = PageOne.initialise <strong>user</strong><br>    , pageTwo = PageTwo.initialise <strong>user</strong><br>    , pageThree = PageThree.initialise <strong>user</strong><br>    }</pre><p>This is fine as long as the user never changes. If there are events in the app’s lifecycle that can change that data then you have created a problem for yourself that you might not have noticed yet.</p><p>The problem is one of ownership. You now have two versions of the truth. RootComponent’s Model and PageOne’s Model. Let’s assume that our user signs out. Who handles this type of action? Most likely the RootComponent:</p><pre>update: Msg -&gt; Model -&gt; (Model, Cmd Msg)<br>update msg model =<br>    case msg of<br>        SignOut -&gt;<br>            ( { model | user = signOut model.user }<br>            , Cmd.none )<br>    ...</pre><p>So we would say in this case that the RootComponent <em>owns </em>the user state. The problem with the code above is that it does not update the copy of the user that we also added to the PageOne Model. We have two source of the truth and they are out of sync all of sudden. Hopefully we at least notice.</p><p>Assuming we do notice, what do we do?</p><h3>Synchronise the data?</h3><p>What we seem to be saying is that when the SignOut action occurs in RootComponent we need to update the model of certain child components as well. One option is to simply do that in the update function of the RootComponent.</p><pre>update : Msg -&gt; Model -&gt; ( Model, Cmd Msg )<br>update msg model =<br>    case msg of<br>        SignOut -&gt;<br>            let<br>                pageOne =<br>                    model.pageOne</pre><pre>                signedOut =<br>                    signOut model.user<br>            in<br>                ( { model<br>                    | user = signedOut<br>                    , pageOne = { pageOne | user = signedOut }<br>                  }<br>                , Cmd.none<br>                )</pre><p>What’s wrong with that? A couple of things. Firstly, we have broken our encapsulation. The RootComponent now needs to know the structure of the PageOne Model. This makes the PageOne Model more difficult to change. Secondly, it’s all too easy to forget to do it. It won’t be immediately obvious that we have a problem.</p><p>We can perhaps fix the first problem by delegating <em>how </em>to update PageOne’s model to a PageOne utility function.</p><pre>update : Msg -&gt; Model -&gt; ( Model, Cmd Msg )<br>update msg model =<br>    case msg of<br>        SignOut -&gt;<br>            let<br>                signedOut =<br>                    signOut model.user<br>            in<br>                ( { model<br>                    | user = signedOut<br>                    , <strong>pageOne = PageOne.updateUser signedOut</strong><br>                  }<br>                , Cmd.none<br>                )</pre><p>This is better. We have regained encapsulation. But the more serious problem remains. There is nothing stopping us from forgetting to do this.</p><p>That function PageOne.updateUser looks a lot like a specialised form of a normal update function doesn’t it? Would it be more palatable if we were just calling the normal update function?</p><pre>update : Msg -&gt; Model -&gt; ( Model, Cmd Msg )<br>update msg model =<br>    case msg of<br>        SignOut -&gt;<br>            let<br>                signedOut =<br>                    signOut model.user</pre><pre>                ( pageOne, pageOneCmd ) =<br>                    PageOne.update <br>                        (PageOneMsg PageOne.signOut) model.pageOne<br>            in<br>                ( { model<br>                    | user = signedOut<br>                    , pageOne = pageOne<br>                  }<br>                , Cmd.map PageOneMsg pageOneCmd<br>                )</pre><p>You might prefer this, but really it’s the same at the end of the day. I still cannot think of a way to make this cascade of updates automatic (or at least enforced by the compiler).</p><h3>A step in the right direction?</h3><p>Maybe we can add the user to the child component’s models and just have a convention that it must be replaced with the parent’s copy on each call to update / view. So RootComponent’s update function might look something like this:</p><pre>update: Msg -&gt; Model -&gt; (Model, Cmd Msg)<br>update msg model =<br>    case msg of<br>        PageOneMsg sub -&gt;<br>            let<br>                (subModel, subCmd) =<br>                    PageOne.update sub model.pageOne<br>            in<br>            ( { model | pageOne = <strong>updateUser model.user subModel</strong><br>                , Cmd.map PageOneMsg subCmd )<br>    ...</pre><pre>-- a general util that can be used from anywhere<br><strong>updateUser : User -&gt; { a | user: User} -&gt; { a | user: User}<br>updateUser user model =<br>    { model | user = user }</strong></pre><p>Now we are not going to get out of sync <strong>but only if everyone remembers that this is the pattern to use</strong>. With this approach we will continue to get caught out from time to time when we forget.</p><h3>Do not allow two copies of volatile data</h3><p>We must conclude that we simply cannot allow there to be two copies of any volatile state. But this takes us back to the problem, how does the PageOne component access the user. The answer is to ensure that any such state is passed in from the parent component along with the child component’s model, but not as part of if. So PageOne’s update signature might end up looking like:</p><pre>update: Msg -&gt; User -&gt; Model -&gt; (Model, Cmd Msg)</pre><p>And if we needed this state in the view we would want to make a similar adjustment to the view signature. Notice that this is quite similar to the approach taken in React where we have props (which is data passed from above that I do not own) and state which is the data that I am in control of myself.</p><p>The big advantage of this approach is that we cannot fail to pass it in from above every time and we do not have two copies of the data any more. Nothing can get out of sync which is very valuable. The downside is that you have to be careful if you are going to make this scale. What happens when I discover another piece of state that is really owned by an ancestor component? I have to add that to the signature as well. All the way down.</p><p>It can add to feeling that there is already a bit too much boilerplate for comfort. But in my view, it is the only real solution. Please let me know if you think there is another option!</p><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a>family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>To learn more, <a href="https://goo.gl/4ofytp">read our about page</a>, <a href="http://bit.ly/HackernoonFB">like/message us on Facebook</a>, or simply, <a href="https://goo.gl/k7XYbx">tweet/DM @HackerNoon.</a></blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72f711ceb244" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/the-importance-of-state-ownership-in-elm-72f711ceb244">The importance of state ownership in Elm</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating an Elm Native module for currency formatting]]></title>
            <link>https://medium.com/hackernoon/creating-an-elm-native-module-for-currency-formatting-c9800e57a908?source=rss-6555944dfe7f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c9800e57a908</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[elm-native]]></category>
            <dc:creator><![CDATA[Boolean Julian Jәlfs]]></dc:creator>
            <pubDate>Sat, 25 Feb 2017 11:02:20 GMT</pubDate>
            <atom:updated>2018-07-13T07:39:30.605Z</atom:updated>
            <content:encoded><![CDATA[<p>Lots of things are very nice in Elm but occasionally you find a gap. For me, currency formatting was such a gap. It’s non-trivial enough to be annoying if you need to deal with different locales and different currencies. Javascript has a perfect api for this in the form of the <a href="https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString">toLocaleString </a>function.</p><p>Elm has an undocumented feature called Native modules allowing you to call javascript functions directly. Of course this is a bad idea and can easily re-introduce all of the type chaos and runtime errors that you were trying to escape. But in a case like this it seems reasonable — why reinvent a perfectly good api?</p><p>The <a href="https://github.com/eeue56/take-home/wiki/Writing-your-first-Elm-Native-module">information I was able to find about how to do this</a> was a little out of date and that’s why I’m writing up how it can be done in Elm 0.18.</p><h3>Create a normal Elm module</h3><p>First step is to create a normal Elm module to expose your function.</p><pre>module Utils.CurrencyFormat exposing (format)</pre><pre>--this is where we import the native module<br>import Native.CurrencyFormat</pre><pre>format : String -&gt; String -&gt; number -&gt; String<br>format culture currency num =<br>    let<br>        res =<br>            Native.CurrencyFormat.format culture currency num<br>    in<br>        case res of<br>            Ok str -&gt;<br>                str</pre><pre>            Err err -&gt;<br>                let<br>                    _ =<br>                        Debug.log &quot;CurrencyFormatError&quot; err<br>                in<br>                toString num</pre><h3>Create your native js file</h3><p>Next create a js file called /src/Native/CurrencyFormat.js. Now, once again, this is <em>not safe</em> so do everything you can to make this js function bullet-proof.</p><pre>var _user$project$Native_CurrencyFormat = (function () {</pre><pre>    var format = function(cultureCode, currency, num) {<br>        try {<br>            var result = num.toLocaleString(cultureCode, {style: &#39;currency&#39;, currency: currency});<br>            return {<br>                ctor: &quot;Ok&quot;,<br>                _0: result<br>            };<br>        } catch (e) {<br>            return {<br>                ctor: &quot;Err&quot;,<br>                _0: e.message<br>            };<br>        }<br>    };<br>    return {<br>        format: F3(format)<br>    };<br>})();</pre><p>This will expose this function to Elm to be called from the module we created in step one. Notice a couple of things: toLocaleString can fail if we give it bad inputs. For this reason we wrap the call in try catch and we return the result as an Elm (Result String String) by supplying the constructor of either Ok or Err. We could choose to pass that result on to the calling code or handle it in our utility function as I have done by just logging it and returning a plain stringified number. It depends how important the error is to you.</p><p>The second thing to note is that I am wrapping the returned function in a call to a mystery F3 function. I am guessing a little bit here, but I’m pretty sure this ensures that the function is appropriately curried so that partial application will work as expected on the Elm side.</p><h3>Configure your app to allow native modules</h3><p>Make the following small change to your elm-package.json file</p><pre>{<br>    &quot;version&quot;: &quot;1.0.0&quot;,<br>    &quot;summary&quot;: &quot;&quot;,<br>    &quot;repository&quot;: &quot;<a href="https://github.com/user/project.git">https://github.com/user/project.git</a>&quot;,<br>    &quot;license&quot;: &quot;BSD3&quot;,<br>    &quot;source-directories&quot;: [<br>        &quot;./client/elm&quot;<br>    ],<br>    <strong>&quot;native-modules&quot;: true,</strong><br>    &quot;exposed-modules&quot;: [],<br>    &quot;dependencies&quot;: {<br>        &quot;elm-lang/core&quot;: &quot;5.0.0 &lt;= v &lt; 6.0.0&quot;,<br>        &quot;elm-lang/html&quot;: &quot;2.0.0 &lt;= v &lt; 3.0.0&quot;,<br>        &quot;elm-lang/http&quot;: &quot;1.0.0 &lt;= v &lt; 2.0.0&quot;<br>    },<br>    &quot;elm-version&quot;: &quot;0.18.0 &lt;= v &lt; 0.19.0&quot;<br>}</pre><h3>Consume your function as normal</h3><p>Your function should work just like a normal Elm function if you’ve done everything right. It will even support automatic currying like any other Elm function. Try it out …</p><pre>toCurrency : number -&gt; String<br>toCurrency =<br>    Currency.format &quot;en&quot; &quot;GBP&quot;</pre><p>I think that in some limited circumstances this is a good solution. But beware, this is an undocumented feature and it can change and be broken at any time so use it at your own risk.</p><blockquote><a href="http://bit.ly/Hackernoon">Hacker Noon</a> is how hackers start their afternoons. We’re a part of the <a href="http://bit.ly/atAMIatAMI">@AMI</a>family. We are now <a href="http://bit.ly/hackernoonsubmission">accepting submissions</a> and happy to <a href="/service/mailto:partners@amipublications.com">discuss advertising &amp; sponsorship</a> opportunities.</blockquote><blockquote>To learn more, <a href="https://goo.gl/4ofytp">read our about page</a>, <a href="http://bit.ly/HackernoonFB">like/message us on Facebook</a>, or simply, <a href="https://goo.gl/k7XYbx">tweet/DM @HackerNoon.</a></blockquote><blockquote>If you enjoyed this story, we recommend reading our <a href="http://bit.ly/hackernoonlatestt">latest tech stories</a> and <a href="https://hackernoon.com/trending">trending tech stories</a>. Until next time, don’t take the realities of the world for granted!</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c9800e57a908" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/creating-an-elm-native-module-for-currency-formatting-c9800e57a908">Creating an Elm Native module for currency formatting</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Replacing the angular 1 router with Elm — Part 4]]></title>
            <link>https://medium.com/hackernoon/replacing-the-angular-1-router-with-elm-part-4-f0ace653d93c?source=rss-6555944dfe7f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0ace653d93c</guid>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Boolean Julian Jәlfs]]></dc:creator>
            <pubDate>Tue, 17 Jan 2017 12:40:02 GMT</pubDate>
            <atom:updated>2017-03-01T07:04:10.428Z</atom:updated>
            <content:encoded><![CDATA[<p>This is part four in a series. You should also read <a href="https://medium.com/@julianjelfs_61852/replacing-the-angular-1-router-with-elm-d71753e74e32#.q661pucta">part 1</a>, <a href="https://medium.com/@julianjelfs_61852/replacing-the-angular-1-router-with-elm-part-2-bf9c84934abf#.kdib3ce9i">part 2</a> and <a href="https://medium.com/@julianjelfs_61852/replacing-the-angular-1-router-with-elm-part-3-d56e40bf251#.tp2toln2g">part 3</a>.</p><p>So we have at least one remaining major problem. When Elm removes the node at the root of our component tree as part of a route change we are potentially removing a large sub-tree that is under angular’s control without telling angular and without giving it a chance to perform its normal cleanup operations. This can and does lead to memory leaks and eventually crashes. You won’t notice this in the sample code because the effect is probably too small.</p><p>To recap, when Elm changes route we trigger a digest loop as follows:</p><pre>function triggerDigest() {<br>    if(!compile) {<br>        return;<br>    }<br>    var $body = angular.element(document.body);            <br>    var $rootScope = $body.injector().get(&#39;$rootScope&#39;);  <br>    var $location = $body.injector().get(&#39;$location&#39;);  <br>    var $compile = $body.injector().get(&#39;$compile&#39;);</pre><pre>    $location.$$parseLinkUrl(window.location.href);<br>    $rootScope.$apply(function() {<br>        $compile($body)($rootScope);<br>    });<br>    observer.disconnect();<br>    listenForRouteChanges = true;<br>}</pre><p>In order to preserve the $destroy behaviour of angular and hopefully avoid memory leaks we need to do something different. We must create a <em>new</em> scope each time from the $rootScope and then compile our root node against that new scope. Then in the next iteration, if that scope we created exists, we will call $destroy on it before we overwrite it with the next new scope. This way, angular will cascade the $destroy call down through the scope hierarchy and everything that needs to be cleaned up will be cleaned up. So the code above will now look like this:</p><pre><strong>let activeScope = null;</strong></pre><pre>function triggerDigest() {<br>    <strong>if(activeScope) {<br>        activeScope.$destroy();<br>    }</strong></pre><pre>    if(!compile) {<br>        return;<br>    }<br>    var $body = angular.element(document.body);            <br>    var $rootScope = $body.injector().get(&#39;$rootScope&#39;);  <br>    var $location = $body.injector().get(&#39;$location&#39;);  <br>    var $compile = $body.injector().get(&#39;$compile&#39;);</pre><pre>    <strong>activeScope = $rootScope.$new();</strong></pre><pre>    $location.$$parseLinkUrl(window.location.href);<br>    <strong>activeScope.$apply(function() {<br>        $compile($body)(activeScope);<br>    });</strong><br>    observer.disconnect();<br>    listenForRouteChanges = true;<br>}</pre><p>Using the AngularJS chrome plugin it is now easy to see that scope hierarchy is now being pruned on each route change as we would expect and hopefully, the memory leak problem goes away (or at least is no worse than it might be with regular angular).</p><p>As before, full source for this proof of concept can be found <a href="https://github.com/travelrepublic/elm-angular-router">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0ace653d93c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/replacing-the-angular-1-router-with-elm-part-4-f0ace653d93c">Replacing the angular 1 router with Elm — Part 4</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Replacing the angular 1 router with Elm — Part 3]]></title>
            <link>https://medium.com/hackernoon/replacing-the-angular-1-router-with-elm-part-3-d56e40bf251?source=rss-6555944dfe7f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d56e40bf251</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angularjs]]></category>
            <dc:creator><![CDATA[Boolean Julian Jәlfs]]></dc:creator>
            <pubDate>Thu, 12 Jan 2017 20:22:20 GMT</pubDate>
            <atom:updated>2017-01-17T12:40:38.922Z</atom:updated>
            <content:encoded><![CDATA[<p>This is part three in a series. You should also read <a href="https://medium.com/@julianjelfs_61852/replacing-the-angular-1-router-with-elm-d71753e74e32#.q661pucta">part 1</a> and <a href="https://medium.com/@julianjelfs_61852/replacing-the-angular-1-router-with-elm-part-2-bf9c84934abf#.kdib3ce9i">part 2</a>.</p><p>To recap, we have a solution which appears to work but we have two competing runtimes trying to control our location and this is causing two serious problems. Firstly, when <em>angular </em>triggers the navigation we end up with two entries in the history queue which messes up the back button. Secondly, when <em>Elm</em> triggers the navigation, angular’s $location service loses track of what page we are on so if your angular code calls something like $location.path() it may get the wrong answer. I want a solution that does not break my angular code so this is not ok.</p><p>And this is where it gets a bit (ok a lot) hacky :( Let’s take these issues one by one. When angular triggers a navigation either by a call to $location service methods or by clicking an anchor tag within an angular component, it will update the browser url and call history.pushState (among other things). Our problem is that we then listen for the $locationChange event and instruct Elm to change route which will trigger <em>another </em>call to history.pushState.</p><p>So one of these calls has to be prevented. My initial instinct was to prevent angular from inserting pushState. But if we do that angular gets into an infinite digest loop as it continuously tries to resolve the difference between what $browser is telling it and what $location is telling it. So it is better to allow angular to do its thing, after all angular is running the show in this navigation. In which case we have to prevent Elm from subsequently adding the second entry.</p><p>We can do this by subscribing to $locationChangeSuccess rather than $locationChangeStart. When the success event fires, we know that angular has already added its history entry and we know that the <em>next </em>entry will be triggered by Elm. So at this point we set a flag to indicate that the <em>next</em> call to pushState should be ignored.</p><pre>$rootScope.$on(&#39;$locationChangeSuccess&#39;, function(e, newUrl, oldUrl){<br>    if(!listenForRouteChanges) {<br>        return;<br>    }<br>    app.ports.newUrl.send(newUrl);<br>    <strong>//at this point angular will have added a history state<br>    //already so we should ignore the next one<br>    ignoreNextPushState = true;</strong><br>});</pre><p>In order to actually drop the next call to pushState we have to intercept / decorate the history api as follows:</p><pre>var ps = window.history.pushState;<br>window.history.pushState = function() {<br>    <strong>if(ignoreNextPushState) {<br>        ignoreNextPushState = false;<br>        return;<br>    }</strong><br>    ps.apply(window.history, arguments);<br>}</pre><p>I warned you this was hacky! But it <em>does</em> take care of our first new problem. But we still face the second problem that angular loses track of the location when Elm initiates the navigation. To solve that will require more hacks I’m afraid.</p><p>When our mutation observer tells us we need to compile the root node we know that we are in an Elm-initiated route change and therefore that angular’s $location service is going to be put out of sync. To avoid this I have found that we can use a private angular api to synchronise it with the real url (yuck) like this:</p><pre>$location.$$parseLinkUrl(window.location.href);</pre><p>Obviously I don’t feel great about this and it has all got a bit more complicated than it originally seemed it would be. But it works and the important thing is that I haven’t had to do anything weird in the Elm code or in the existing angular code. The hackery is self contained in one place and when the time comes it can simply be deleted.</p><h3>But there is a serious problem!</h3><p>We are allowing Elm to remove elements from the DOM that represent angular components. This means that angular is not doing any of its normal cleanup and this means memory leaks! In <a href="https://medium.com/@julianjelfs_61852/replacing-the-angular-1-router-with-elm-part-4-f0ace653d93c#.c0fsjdt04">part four</a> I will see if we can deal with that.</p><p>As before, full source for this proof of concept can be found <a href="https://github.com/travelrepublic/elm-angular-router">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d56e40bf251" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/replacing-the-angular-1-router-with-elm-part-3-d56e40bf251">Replacing the angular 1 router with Elm — Part 3</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Replacing the angular 1 router with Elm — Part 2]]></title>
            <link>https://medium.com/hackernoon/replacing-the-angular-1-router-with-elm-part-2-bf9c84934abf?source=rss-6555944dfe7f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf9c84934abf</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[elm]]></category>
            <dc:creator><![CDATA[Boolean Julian Jәlfs]]></dc:creator>
            <pubDate>Wed, 11 Jan 2017 21:19:50 GMT</pubDate>
            <atom:updated>2017-01-12T20:23:08.409Z</atom:updated>
            <content:encoded><![CDATA[<p>This is a follow up post to <a href="https://medium.com/@julianjelfs_61852/replacing-the-angular-1-router-with-elm-d71753e74e32#.2fd4y8xip">part one</a>.</p><p>Now we are successfully rendering angular components beneath the Elm router which is great. But there is a problem. If we are trying to migrate an existing angular app that used the angular router then there is a very good chance that we are using the $location service to perform programmatic route changes for example:</p><pre>$location.path(&#39;/pagefour/1234&#39;);</pre><p>This is not going to work any more because Elm is in control. So we need to find a way to tell Elm to change the route rather than telling angular to change route. And preferably we need to do this without changing our angular code in any intrusive way (because we might have a lot of it).</p><p>One way do this is to decorate the $location service and override its default behaviour to send a message to an inbound Elm port so that Elm can take over. Something like this:</p><pre>const app = Elm.Main.embed(root);</pre><pre>angular.module(&#39;MyApp&#39;, [])<br>    .config(function($locationProvider, $provide) {<br>    <br>    $locationProvider.html5Mode(true);</pre><pre>    $provide.decorator(&#39;$location&#39;, [&#39;$delegate&#39;, <br>        function $locationDecorator($delegate) {<br>            const p = $delegate.path;<br>            <strong>$delegate.path = function(url) {<br>                app.ports.newUrl.send(url);<br>            }</strong><br>            return $delegate;<br>        }]);<br>});</pre><p>This will intercept all calls to $location.path and send the url to our newUrl port. On the Elm side we need to define that port as follows:</p><pre>port newUrl : (String -&gt; msg) -&gt; Sub msg</pre><p>and then we need to subscribe to that port so our subscriptions function becomes:</p><pre>subscriptions : Model -&gt; Sub Msg<br>subscriptions model =<br>    newUrl NewUrl</pre><p>We are already handling the NewUrl Msg in our update function and everything appears to work.</p><h3>But there is still a problem</h3><p>Anchor tags will still not work. So it turns out that decorating $location.path is not the right approach because it is only one way that angular can change the location, we need to cover them all. The solution is to listen out for angular’s $locationChangeStart event and send the message to our Elm port when that happens.</p><pre>angular.module(&#39;MyApp&#39;, []).run(function($rootScope) {<br>    $rootScope.$on(&#39;$locationChangeStart&#39;, (e, newUrl) =&gt; {<br>        app.ports.newUrl.send(newUrl);<br>    });<br>});</pre><p>There is one final issue with this. We actually don’t want to listen to the angular event if the route change was initiated by <em>Elm </em>— only if it was initiated by angular. So we can just create a flag and set it when Elm triggers a route change (we know when that happens because we are listening on an outbound port from Elm) and modify our listening code slightly.</p><pre>angular.module(&#39;MyApp&#39;, []).run(function($rootScope) {<br>    $rootScope.$on(&#39;$locationChangeStart&#39;, (e, newUrl) =&gt; {<br>        <strong>if(!listenForRouteChanges) {<br>            return;<br>        }</strong><br>        app.ports.newUrl.send(newUrl);<br>    });<br>});</pre><p>When we have finished handling the Elm initiated route change we just set that listForRouteChanges flag back to true.</p><h3>But there is still a problem</h3><p>The browser’s history is getting messed up, more details and some sort of solution in <a href="https://medium.com/@julianjelfs_61852/replacing-the-angular-1-router-with-elm-part-3-d56e40bf251#.k0v54hssi">part three</a> …</p><p>As before, full source for this proof of concept can be found <a href="https://github.com/travelrepublic/elm-angular-router">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf9c84934abf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/replacing-the-angular-1-router-with-elm-part-2-bf9c84934abf">Replacing the angular 1 router with Elm — Part 2</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Replacing the angular 1 router with Elm — Part 1]]></title>
            <link>https://medium.com/hackernoon/replacing-the-angular-1-router-with-elm-d71753e74e32?source=rss-6555944dfe7f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d71753e74e32</guid>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angularjs]]></category>
            <dc:creator><![CDATA[Boolean Julian Jәlfs]]></dc:creator>
            <pubDate>Tue, 10 Jan 2017 08:21:58 GMT</pubDate>
            <atom:updated>2017-01-11T21:23:20.190Z</atom:updated>
            <content:encoded><![CDATA[<p>If you are trying to migrate away from angular 1 (and you aren’t interested in angular 2) it seems that you have two options: you can either try to replace individual components and eat angular from the inside out, or you can try to eat it from the outside in by replacing the router first.</p><p>I am interested in trying to get out from underneath the angular 1 router and so I really want to go for the latter option. This enables me to start treating angular 1 as just one way to render components rather than a framework that’s in charge of everything.</p><p>The technology I’m most interested in migrating towards is Elm and I was inspired by <a href="https://www.youtube.com/watch?v=ar3TakwE8o0">Richard Feldman’s talk on Web Components in Elm</a> and it seemed to me that we ought to be able to achieve something similar with angular 1 components / directives.</p><p>It is straightforward to render an angular directive using the “node” function from Elm’s Html.Attributes module; the problem is that it will not do anything unless the angular framework knows that it has been added to the DOM and gets a chance to compile it.</p><p>For example, let’s say that I have the following angular component:</p><pre>angular.module(&#39;MyApp&#39;, [])<br>    .component(&#39;pageOne&#39;, {<br>    template: &#39;&lt;div&gt;Page One&lt;/div&gt;&#39;,<br>    controller: function PageOneController () {<br>        console.log(&#39;we are in page one&#39;);<br>    }<br>});</pre><p>I can render this from Elm like this:</p><pre>node &quot;page-one&quot; [] []</pre><p>But it does me no good because angular knows nothing about it. We need to tell angular about this.</p><p>Elm is emitting virtual DOM of course and we have no obvious way to know when the real DOM has been updated.</p><h3>Mutation Observers</h3><p>So with a client side routing solution we are effectively swapping content in and out of a single root node when the route changes. We can use a mutation observer to monitor that root node and then instruct angular to compile the contents when there is a change.</p><p>Something like this:</p><pre>var root = document.getElementById(&#39;root&#39;);<br>var observer = new MutationObserver(triggerDigest);<br>observer.observe(root, { childList: true, subtree: true });</pre><pre>function triggerDigest() {<br>    var $body = angular.element(document.body);            <br>    var $rootScope = $body.injector().get(&#39;$rootScope&#39;);  <br>    var $compile = $body.injector().get(&#39;$compile&#39;);<br>    $rootScope.$apply(function() {<br>        $compile($body)($rootScope);<br>    });<br>}</pre><p>So here we obtain a reference to the root element into which we will be embedding the Elm app. We create a mutation observer which will call a triggerDigest function. That function obtains a reference to angular’s $rootScope and its $compile service. It then compiles the whole tree against the root scope.</p><h3>Infinite loops</h3><p>But we have a problem. As it stands we are monitoring the whole subtree and compiling the angular directive will cause more mutation and trigger another compile. This is going to result in an infinite spiral of compilation and mutation and kill the page.</p><p>One solution is to have Elm tell us when we should start observing and then stop observing as soon as we have compiled. This can be done using ports. We can create an outbound port in Elm like this:</p><pre>port watchDom : String -&gt; Cmd msg</pre><p>Then we need to send a message to this port when the url changes:</p><pre>update : Msg -&gt; Model -&gt; ( Model, Cmd Msg )<br>update msg model =<br>    case msg of<br>        UrlChange location -&gt;<br>            ( { model | route = Url.parsePath route location }<br>            , <strong>(watchDom &quot;&quot;)</strong><br>            )</pre><p>We can then modify our javascript as follows:</p><pre>var root = document.getElementById(&#39;root&#39;);<br><strong>var app = Elm.Main.embed(root);</strong><br>var observer = new MutationObserver(triggerDigest);</pre><pre><strong>app.ports.watchDom.subscribe(function(msg) {<br>    observer.observe(root, { childList: true, subtree: true });<br>});</strong></pre><pre>function triggerDigest() {<br>    var $body = angular.element(document.body);            <br>    var $rootScope = $body.injector().get(&#39;$rootScope&#39;);  <br>    var $compile = $body.injector().get(&#39;$compile&#39;);<br>    $rootScope.$apply(function() {<br>        $compile($body)($rootScope);<br>    });<br>    <strong>observer.disconnect();</strong><br>}</pre><p>And that will break the loop for us and leave us with the beginnings of a viable solution. Not sure how efficient it is, but it appears to work at least.</p><p>One caveat with using ports in this way is that it means that the 0.18 debugger is not going to work properly. It would be possible to avoid the use of ports by wrapping the `history.pushState` function and tracking the `popstate` event. One advantage of ports is that it allows us to supply some meta data about the route we are navigating to e.g. does it contain content that needs compiling perhaps.</p><h3>There is still a problem</h3><p>In <a href="https://medium.com/@julianjelfs_61852/replacing-the-angular-1-router-with-elm-part-2-bf9c84934abf#.1lylajdpa">part two</a> I will explore how to deal with internal angular links.</p><p>Full source code for this proof of concept can be found <a href="https://github.com/travelrepublic/elm-angular-router">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d71753e74e32" width="1" height="1" alt=""><hr><p><a href="https://medium.com/hackernoon/replacing-the-angular-1-router-with-elm-d71753e74e32">Replacing the angular 1 router with Elm — Part 1</a> was originally published in <a href="https://medium.com/hackernoon">HackerNoon.com</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>