<?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 muyiwa akin-ogundeji on Medium]]></title>
        <description><![CDATA[Stories by muyiwa akin-ogundeji on Medium]]></description>
        <link>https://medium.com/@nohkachi?source=rss-1b66a948a46b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EBriAFdW8Z_xNYSkOyz1og.jpeg</url>
            <title>Stories by muyiwa akin-ogundeji on Medium</title>
            <link>https://medium.com/@nohkachi?source=rss-1b66a948a46b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 16:11:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@nohkachi/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[Introducing Ann Haliszt — a genAI BI tool for SMB owners]]></title>
            <link>https://medium.com/@nohkachi/introducing-ann-haliszt-a-genai-bi-tool-for-smb-owners-cd4e129d678a?source=rss-1b66a948a46b------2</link>
            <guid isPermaLink="false">https://medium.com/p/cd4e129d678a</guid>
            <category><![CDATA[gen-ai-for-business]]></category>
            <category><![CDATA[small-business]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[business-intelligence]]></category>
            <category><![CDATA[llm]]></category>
            <dc:creator><![CDATA[muyiwa akin-ogundeji]]></dc:creator>
            <pubDate>Tue, 11 Feb 2025 08:46:57 GMT</pubDate>
            <atom:updated>2025-02-11T08:46:57.942Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introducing Ann Haliszt — a genAI BI tool for SMB owners</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NcP_4WRmdpoIXzLx_zmv5g.png" /><figcaption>Ann Haliszt startup screen</figcaption></figure><p>Throughout this article series (<a href="https://medium.com/@nohkachi/how-to-build-a-python-desktop-app-with-pywebview-and-flask-73025115e061">part 1</a>, <a href="https://medium.com/@nohkachi/how-to-package-a-python-desktop-app-for-windows-with-briefcase-a270cf05da17">part 2</a>), I&#39;ve continually referenced the desktop app I built for Windows called <strong>Ann Haliszt</strong> (pronounced <em>analyst</em>). In this article, I&#39;d like to discuss Ann with you. I intend to present the business case for Ann Haliszt, share what makes it different, explain how it was built (the tools, etc I used), and provide a deep dive into how it works. Let&#39;s go!</p><h3>The Business Case for Ann Haliszt</h3><p>Let&#39;s assume you run a small business providing moving services to your town or city. You&#39;re doing ok. You understand how to lead your team, you know how to handle your customers, and you understand how to market your business, but you&#39;re neither an accountant nor a data analyst — however, you do have someone on staff who keeps your books (finance and operations) on Excel.</p><p>You know that you&#39;re doing well, but <em>just how well are you doing</em>? If only you could explore your data and ask all the questions that you really wanted answers to, how much better would your operations be? How much more would you make? For now, the best you have in terms of insight is your account statement from the bank, your financial health statement from your accountant/tax professional, and basic reports from your bookkeeper.</p><p>Across the World, there are millions of people in all sorts of Industries who face this exact same problem.</p><p><em>This is the problem Ann Haliszt is here to solve.</em></p><blockquote>Unlock your data’s secrets with Ann Haliszt. Say farewell to spreadsheets and complex BI tools — upload your CSV or Excel files, ask questions in plain English, and let Ann, your expert data analyst, handle the rest. Receive instant insights in user-friendly visualizations, with the option of email recaps for future reference. Ann Haliszt is available 24/7, offering real-time database queries for efficient decision-making. No technical jargon — just clear visualizations and always-accessible answers. Elevate your business decisions with Ann Haliszt, making BI simple and decisions smarter.</blockquote><h4>What makes Ann Haliszt different</h4><p>There are quite a few genAI BI/Data Analysis tools out there, but very few target relatively low-tech SMB owners. Ann Haliszt is for the small business owner, the mom-and-pop shop, and the solo entrepreneur who just wants something that works!</p><p>Here&#39;s why Ann Haliszt is different from the rest:</p><ol><li><em>Plain English, zero jargon:</em> Ask your questions like you would a human, no technical mumbo jumbo needed.</li><li><em>Visualizations that speak a thousand words:</em> See your data come alive with clear and insightful charts.</li><li><em>Always on call:</em> Get answers anytime, anywhere, with no need to wait for the accountant, bookkeeper, or IT support.</li><li><em>Smarter decisions, faster:</em> Make data-driven choices with confidence, based on accurate and up-to-date insights.</li><li><em>Data Privacy:</em> Rest easy knowing your data is in good hands — your hands! Your data never leaves your system. Data analysis is done on your laptop or desktop, and the selected files are deleted the moment your session ends. Your privacy matters!</li></ol><h3>How Ann Haliszt is built</h3><p>As you may have guessed from the previous articles in this series Ann Haliszt is built with the following tools:</p><ol><li><em>Flask</em> as the embedded server</li><li><em>OpenAI Python SDK</em> (leveraging the gpt4o-mini and gpt-o3-mini models)</li><li><em>Svelte</em> for the UI</li><li><em>Pywebview</em> to convert the Flask app into a desktop app</li><li><em>Briefcase</em> to package the Pywebview app as a Windows MSI package</li></ol><p>Using these tools, we&#39;re able to create something that just works! OpenAI for the top performing LLM models (yes I know about Deepseek etc, you&#39;re free to use them if you wish 🤪). Best of all, we have a tool that lets us do more than any version of ChatGPT without exposing your confidential data to potential leakages — <em>how cool is that</em>?</p><h3>How it works</h3><p>Ann Halsizt uses your OpenAI API key to authenticate access to the API, if the API key is valid, it allows you to select one or more CSV/Excel files for analysis.</p><h4>EDA</h4><p>The first thing it does is what is technically called <em>Exploratory Data Analysis</em> (EDA), Ann Haliszt uses OpenAI to generate code that explores your data, then it provides you with a <em>summary/overview</em> of what your data is about, backs it up with one or more charts, and finally presents <em>lines of inquiry</em> i.e. directions you can explore — to investigate the data more fully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*3avh0hq9aDcLii1Upibs9A.gif" /><figcaption>Ann Haliszt EDA</figcaption></figure><h4>Ice Breaker</h4><p>Sometimes, you have no idea how to dig into your data. Following on the EDA, Ann Haliszt provides lines of inquiry that you can use to generate Ice breaker questions. These questions can be used to initially explore your data so you are familiar enough with it to ask more pertinent questions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GD2yKYmBn4B8X9QTyAXwbQ.png" /><figcaption>Ice Breaker questions</figcaption></figure><p>Simply click on any question to kick the analysis process off, or type in your own question.</p><h4>Charts and Visualizations</h4><p>Getting charts to visualize the answer to your question is super simple. If the question you asked can best be answered with a chart, Ann Haliszt will do so and render the chart as a static image (interactive charts available on demand).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*D5xVV44oATK4n_MkyxNg4Q.gif" /><figcaption>Charts and visualizations</figcaption></figure><h4>Text responses</h4><p>For your queries that can best be answered by a text, Ann Haliszt responds with a user-friendly text string, no jargon, just simple, straightforward English that even a 12-year-old can understand!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*sp9vMpwaX2lJ7eOfcMNS5w.gif" /><figcaption>Text response</figcaption></figure><h4>Follow up questions</h4><p>Every response by Ann Haliszt is accompanied by a set of follow-up questions implemented as <em>quick action buttons</em>. These allow you to optionally dive deeper down a path that you started with your previous question. They allow you to dive really deep into understanding something in your data — they&#39;re awesome!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4xTRlrVRlzClfh5fTLk7Ww.png" /><figcaption>Follow up questions</figcaption></figure><h4>Chat summary</h4><p>The basic version of Ann Haliszt will allow you to download a summary of the chat as a .<em>TXT file</em>. Optionally, you can have the chat summary sent as an email. This makes it easy to keep track of all the info you gleaned in your chat session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XwtZgt5Z7Lzr9qbHfMttLA.png" /><figcaption>Download chat summary as a .txt file</figcaption></figure><p>After the text file has been downloaded, Ann Haliszt will render the summary to the chat UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9wIiSFSXZ9tNTHRa6QpuFA.png" /><figcaption>Chat summary rendered to UI</figcaption></figure><h3>Wrap Up</h3><p>This is a data-driven world. As the owner of an SMB, <em>can you afford to not know what makes your business tick</em>? Ann Haliszt can help you make sense of your data without stress!</p><p>I initially created Ann to help out a couple of my friends who owned SMBs and were looking to go beyond what ChatGPT could do for them. I believe it can help you also, why not reach out to test drive it and help in making it even more amazing?</p><p>I look forward to hearing from you.</p><h3>Help needed</h3><p>I’d like to build a sleeker and more attractive UI, unfortunately for me, it’s beyond my skills. I’d be grateful to anyone who’d like to collaborate with me on this. Svelte skills would be preferred so you can understand what I’ve done already. Please give me a shout at <a href="/service/mailto:annhaliszt@yahoo.com">annhaliszt@yahoo.com</a></p><p>I’m also looking for early adopters. Owners or management heads of an SMB (Small or Medium Business) who would like to test run Ann Haliszt for a significant discount before we go public. My assumption (based on feedback from some testers) is that you are not a finance professional so you don’t have data analysis skills, but you do have data you’d like to dig into to help inform your business decisions.</p><p>I’d be very happy to hear from you, your feedback could make this a more awesome tool for you and thousands like you. Please give me a shout at <a href="/service/mailto:annhaliszt@yahoo.com">annhaliszt@yahoo.com</a></p><p>Do you need a highly skilled developer to help you translate your genAI idea into a product or service? I’m available to work in a consulting or development role — please give me a shout at <a href="/service/mailto:oakingoundeji@gmail.com">oakingoundeji@gmail.com</a></p><p>Thanks all 🙌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd4e129d678a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to package a python desktop app for Windows with briefcase]]></title>
            <link>https://medium.com/@nohkachi/how-to-package-a-python-desktop-app-for-windows-with-briefcase-a270cf05da17?source=rss-1b66a948a46b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a270cf05da17</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[gen-ai-for-business]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[data-analysis]]></category>
            <dc:creator><![CDATA[muyiwa akin-ogundeji]]></dc:creator>
            <pubDate>Tue, 04 Feb 2025 09:16:52 GMT</pubDate>
            <atom:updated>2025-02-11T08:53:48.121Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*Xo6sJQrGXokP6MtFxd7oPQ.png" /><figcaption>briefcase logo</figcaption></figure><p>This is part 2 in a 3-part series where I share my experiences building a Python desktop app using pywebview and flask, and then packaging it for Windows using Briefcase. <a href="https://medium.com/@nohkachi/how-to-build-a-python-desktop-app-with-pywebview-and-flask-73025115e061">Part 1</a> discussed the use of pywebview to build the desktop app. This article will explain my struggles to package the app for Windows, my reason for choosing Briefcase, and share how to effectively use Briefcase to package an MSI installer for Windows. <a href="https://medium.com/@nohkachi/introducing-ann-haliszt-a-genai-bi-tool-for-smb-owners-cd4e129d678a">Part 3</a> shares the desktop app I built using the techniques explained in the rest of this article.</p><h3>STATUS QUO</h3><p>We&#39;ve built what we think is an awesome desktop app. We plan to make it easy for owners and top management of SMBs to query their data files with natural language and get expert analysis in text or charts.</p><p><em>But there&#39;s a problem.</em></p><p>Our target customers aren&#39;t devs. If they&#39;re not data analysts despite running a successful SMB, then they&#39;re surely not going to be interested in running a Python app, they&#39;ll want something that just works, something they&#39;re familiar with — something that&#39;s <em>windowsy</em>.</p><p>What to do?🤔</p><p>We must find a way to convert our Python app into a desktop app that runs on Windows, something they can install simply, and use without thinking much. This article shares my experiences in making this so.</p><h3>BACKGROUND</h3><p>An earlier version of Ann Haliszt was packaged for Windows using Pyinstaller, I did struggle a bit, but with the help of my buddies (Gemini, ChatGPT, Claude, and Le Chat — yes, I needed all four of them, go figure 🤪) I was able to build a Pyinstaller spec file that worked.</p><p>Now I could create a Windows <em>.exe</em> file — all&#39;s well with the world.</p><p>But then, OpenAI released improved models (specifically the o1 series reasoner models), I also had improved as an LLM engineer between the previous version and the OpenAI model releases, and so I did what any good dev would do - <em>I made improvements to the app for the benefit of the users.</em></p><p>And that&#39;s where the trouble started. For some weird reason, I couldn&#39;t get Pyinstaller to work anymore.</p><p>What changed?</p><p>Ubuntu 24.04 LTS was now generally available from the last time I used Pyinstaller (on Ubuntu 22.04 LTS), since my system kept screaming at me to upgrade, I did. I&#39;d also upgraded my dev env i.e. system dependencies. The upgrades wiped out the virtual envs I&#39;d set up initially, so I created new ones using the virtualenv package for Ubuntu. I&#39;d have thought all would be well — but no joy 😥.</p><p>I couldn&#39;t let something like this get in the way of the app. So I turned again to my buddies — we spent 2 days on this, then by mutual agreement, we decided it was a dead end. Pyinstaller just wasn&#39;t going to work for me. I think I&#39;m a fairly competent dev, and I&#39;m a fair hand at reading docs, I&#39;m also quite good (if I say so myself) at using LLMs to figure stuff out, so this was a blow for me.</p><p>The only available option was to look for alternatives to Pyinstaller. My buddies suggested the following:</p><ol><li>cx_freeze</li><li>Nuitka</li><li>pyOxidizer</li><li>briefcase</li><li>shiv</li></ol><p>No choice, I had to work my way through the list. My criteria are straightforward, I want to read the docs, understand everything clearly, have no questions about any part of the config etc, and have everything just work. I wanted something that was similar to the way I write articles - no hard thinking, no sweating, just straightforward explanations. Lets see how things went.</p><h4>cx_freeze</h4><p>My first problem - <a href="https://cx-freeze.readthedocs.io/en/stable/overview.html">too many options</a>.</p><p>I wanted a single path from tool installation, and file config, to running the tool and generating the installer. My experience with Pyinstaller is that I can define an entry point file, the tool would be able to traverse the directory tree and it would be able to pull in all the files used in the app. It would be able to install the dependencies by detecting the requirements file, any extra folders, etc that the app required, I&#39;d be able to specify and things would just work.</p><p>I looked at the <a href="https://cx-freeze.readthedocs.io/en/stable/setup_script.html">docs</a> for the setup script, maybe I&#39;d be able to figure something out, but it left me even more confused, I asked my buddies, and they gave different answers, so I realized that the docs had probably changed from what they knew. Ok, enough of this, next!</p><h4>nuitka</h4><p>Ok, so the <a href="https://nuitka.net/user-documentation/">docs</a> are more straightforward. All good so far.</p><p>I got an initial build working for Ubuntu using the <a href="https://nuitka.net/user-documentation/tutorial-setup-and-build.html">quick start</a>. Nice, I had a distributable up and running in less than 2 minutes, awesome 🥳. So the next step is to build a version that I can use on another Ubuntu system i.e. I need to use the <a href="https://nuitka.net/user-documentation/tutorial-setup-and-build.html#distribute">standalone</a> flag. So I start the process, 5 minutes, 10, 15, 20… getting ridiculous, 30 minutes still not completed — naah, there&#39;s no way this can work with the github CI. Next!</p><h4>pyOxidizer</h4><p>So, my buddies had warned me that this had a steep learning curve, but what choice did I have? I start by installing Rust, setting up the env, etc. So I begin to create the config file (<em>.bzl</em>). There are 3 things I want to be able to do:</p><ol><li>specify the entry point</li><li>ensure all dependencies are installed</li><li>specify any required folders in the app</li></ol><p>I can easily do steps 1 and 2, fantastic. <em>Not sure about step 3, but lemme get something up and running first.</em> So I kick off the build process. I wait, 5 minutes, 10 minutes — no joy. Is it my internet? I change networks. Try again. No joy. What&#39;s happening 🤔? I thought this would be it. Ok, nothing to do, next!</p><h3>Briefcase</h3><p>This has a clear tutorial, although it kinda wants to use its own UI toolkit (Toga), but I can manage it. So, I set up an empty folder, and created a new Briefcase project so the tool can generate the directory structure and config file.</p><p>I reviewed the docs, very clear and straightforward, <em>could this be it?</em> I read the tutorial to the end, and reviewed the docs again - it all makes sense, it seems too good to be true, but I can&#39;t detect any issues — lets give it a shot.</p><p>The rest of this article explains how to use Briefcase to package a Python desktop app for Windows. This is the <a href="https://github.com/oakinogundeji/briefcase_tutorial">repo</a> for this article, please clone it to follow along. Let us go!</p><h4>Directory Structure</h4><p>Briefcase requires a very specific directory structure. It&#39;s a good thing as it helps ensure that the app is structured in a more pythonic way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/443/1*l_Xzx5yD4jLbnP5PDv5w7g.png" /><figcaption>briefcase directory struture</figcaption></figure><p>The app has to be within a folder that is named for the project e.g. <em>annhaliszt</em>. The top-level files are <em>CHANGELOG</em>, <em>LICENSE,</em> and the <em>pyproject.toml</em> files.</p><p>Inside the <em>annhaliszt</em> folder, we see 3 files and 2 folders. <em>app.py</em> and the <em>be</em> folder should be familiar from the previous article. The new files are <em>__init__.py</em>, and <em>__main__.py</em>, while the new folder is labelled <em>resources</em>.</p><p>The <em>__init__.py</em> file is a Python convention that indicates that the <em>annhaliszt</em> folder is a Python package. It&#39;s empty, but required under Python conventions.</p><p>The entry point is <em>__main__.py</em>. I actually tried to move the code from <em>app.py</em> into <em>__init__.py</em> in order to skip using <em>__main__.py</em> file, however, Briefcase insists that this <em>__main__.py</em> file must exist. It&#39;s not a biggie TBH, so I embraced it. Lets look at this file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ade60687602c6db4daaa8bc5055f44a7/href">https://medium.com/media/ade60687602c6db4daaa8bc5055f44a7/href</a></iframe><p>It&#39;s a very short file.</p><p>Line 1 simply imports the <em>main</em> function from <em>app.py</em>. Line 3 is a python convention that defines what must happen if the module is invoked directly, at line 4, we see that what will happen is that the <em>main</em> function of <em>app.py</em> will be executed.</p><p>Lets see app.py.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd832951fdaf709452e72e3f2f115ec1/href">https://medium.com/media/bd832951fdaf709452e72e3f2f115ec1/href</a></iframe><p>This file should be very familiar from the previous article. The only change is on line 4, where rather than directly importing functions from the <em>be</em> directory, we actually wrap the import in a package call i.e. prefix with <em>annhaliszt</em>.</p><p>With these files out of the way, the most interesting file for us is the Breifcase config file i.e. <em>pyproject.toml</em> file. Lets explore it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/987755e231b700058f70a91f451cdc3d/href">https://medium.com/media/987755e231b700058f70a91f451cdc3d/href</a></iframe><p>Let me say that the <a href="https://briefcase.readthedocs.io/en/stable/reference/configuration.html#project-configuration-options">docs</a> are very good. This is how docs should be written, simple, stritghforward, intuitive. I was able to easily make the tweaks I wanted in order to customize the build for Ann Haliszt.</p><p>One awesome thing IMO is that all you need is a single <em>toml</em> file where you can define the config for different platforms and Briefcase will do the rest.</p><p>Line 2 declares the base config for the project. The following are the directives that config this section.</p><p>Line 3 is the formal name of the app. In our case we call it Ann Haliszt. Line 4 is a reverse domain name that is used to generate a unique ID for the app. Line 6 is where we specify a URL that can provide info about the app e.g. your brochure website.</p><p>FYI, both lines 4 and 6 can use dummy data if real addresses are not available. Line 7 defines the location to the LICENSE file. I&#39;m using the placeholder I got when I ran the following command:</p><pre>briefcase new</pre><p>Line 11 starts another set of config, this time configs specific to the app itself. Line 12 is the name that is displayed to the app user. Lines 27 and 28 are directives to replace the default icon for the installer package. There&#39;s an interesting quirk here that I&#39;d like to share.</p><p>For a Windows app, all we need is a single <em>.ico</em> file. <em>Notice that the extension of the icon is not specified, simply the path to the icon name</em>. For Ubuntu, something interesting happens, we need to create multiple <em>.png</em> files for different icon sizes e.g. <em>ann_haliszt-16.png</em>, <em>ann_haliszt-32.png</em>, <em>ann_haliszt-64.png</em>, <em>ann_haliszt-128.png</em>, <em>ann_haliszt-256.png</em>, and <em>ann_haliszt-512.png</em>. If we don&#39;t do this, the default icon will be used instead — so take note! I discovered this quirk when I ran the following command and reviewed the terminal output:</p><pre>briefcase build</pre><p>Line 30 defines the python package that should be used as the source code of the app. This is why briefcase requires the <em>__main__.py</em> file as a convention. Line 34 is interesting, for an Ubuntu app this is not required. However, when I omitted this directive in this section for a Windows app, the build threw an error. I&#39;m not sure why, but by inserting this directive, the issues were fixed. The purpose of this directive i.e. the <em>requires</em> statement - is to specify what dependencies should be installed for the app. We can simply use the contents of the <em>requirements.txt</em> file but structured for a Python list/array.</p><p>Line 94 defines the directives for all Linux platforms, line 95 defines the dependencies required if this app is built solely for Linux platforms, as I mentioned earlier, this was sufficient when I packaged for Ubuntu.</p><p>Line 155 begins the directives which are specific to the Debian family of Linux platforms, this is required for Ubuntu. Line 156 specifies the OS dependencies which should be present at build time on the Ubuntu target. I got these from the pywebview <a href="https://pywebview.flowrl.com/guide/installation.html#linux">docs</a>. Line 164 specifies the run time dependencies for the Ubuntu target.</p><p>Line 171 begins the directives for the Windows platform. Line 173 specifies the dependencies for the app, line 233 controls whether on a Windows machine, the app is installed system wide (<em>for all users</em>) or for the logged in user only - We set it to system wide.</p><p>Line 235 is a flag that controls how the app is installed, we want only the app name to be used in crafting the path, and don&#39;t want our name (as the dev) included.</p><p>Again, the config of the toml file is clear, and apart from few quirks, it&#39;s quite easy to understand and tweak. <em>I look forward to your feedback on how you improved this.</em></p><p>The next interesting file is the github actions file. Briefcase is quite helpful in that they have a github actions <a href="https://briefcase.readthedocs.io/en/stable/how-to/ci.html#workflow-file-contents">template</a> that we can modify. We extracted a Windows specific version for Ann Haliszt, lets review it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/446c669d96a13e882cfe084b9d085c5c/href">https://medium.com/media/446c669d96a13e882cfe084b9d085c5c/href</a></iframe><p>The 2 most interesting directives are lines 28 and 32. Lets explore what they mean.</p><p>Line 28 tells GitHub to build the app in test mode ( --test) within the bundled app env, also, to not expect any user input ( --no-input) and if there&#39;re any error logs, to oupt them ( --log).</p><p>Line 32 tells Github to package the Windows app installer (.MSI) by updating and recompiling ( --update) after the previous step, performing the bare minimum signing that will result in an app that can run on a local machine (--adhoc-sign), while testing and logging as on line 28.</p><p>I had absolutely no issues building on github CI. It was an awesome experience and I was very pleased and relieved.</p><h4>LOCAL DEV AND TEST</h4><p>So what about locally? How do we test etc with briefcase? Glad you asked.</p><pre>briefcase dev</pre><p>We run this command after setting up the virtual env (see the <a href="https://github.com/oakinogundeji/briefcase_tutorial/blob/main/README.md">README</a> in the repo for guidance). <em>briefcase dev</em> will run the app in developer mode, wait a few minutes and you&#39;ll see the following terminal screen:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dzriYlDvZV14ukUL3N0Eig.png" /><figcaption>briefcase dev</figcaption></figure><p>notice that it clearly states that it is running in dev mode. Also, the app it self will startup with a screen like below (for Ann Haliszt):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lbNDbKYh0apjUzqkB7eliQ.png" /><figcaption>app screen</figcaption></figure><p>You can make any dev mods to the code required to have a working app and continue to test/iterate with <em>briefcase dev</em> until you&#39;re satisfied that all is well. Did you notice that you didn&#39;t need to <em>pip install</em>? Awesome!</p><pre>briefcase run</pre><p>This command starts the app, using the packaged version of the app code. By default, it targets the current platform’s default output format. Similar to briefcase dev, there&#39;s a terminal output and the app screen. Since the app screen is the same, we&#39;ll skip it, but the terminal output is different from <em>briefcase dev</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NnlEhGrCl1ioXNbn9hdlRw.png" /><figcaption>briefcase run</figcaption></figure><p>If you pay attention to the terminal output, you&#39;ll notice that it actually starts the app binary, look at the line starting with &quot;<em>Built</em> &quot;. If the app works as expected with this command, then you have full confidence that it actually will work as anticipated after it&#39;s packaged.</p><pre>briefcase package</pre><p>As mentioned earlier, this creates an installer for the platform the tool is running on, in our course a <em>.deb</em> installer for Ubuntu. The terminal output looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sh4A9497OPgi1Ax5BSPhXg.png" /><figcaption>briefcase package</figcaption></figure><p>Notice that it actually reports the build of a <em>.deb</em> file with naming and semantic versioning as derived from the <em>toml</em> file. The actual <em>.deb</em> looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*Ri4fmHmOwNlTvtys4wCjyQ.png" /><figcaption>.deb file</figcaption></figure><h3>Wrapping up</h3><p>We&#39;ve reviewed my journey to adopting Briefcase as the packaging tool for Python desktop apps, and also explored how to tweak the default config of Briefcase to ensure that we can use it without issues. <em>I look forward to your own experiences with this tool.</em></p><p>The next article will deep dive into An Haliszt, why I built it, and how to use it — stay tuned!</p><h3>Help needed</h3><p>I’d like to build a sleeker and more attractive UI, unfortunately for me, it’s beyond my skills. I’d be grateful to anyone who’d like to collaborate with me on this. Svelte skills would be preferred so you can understand what I’ve done already. Please give me a shout at <a href="/service/mailto:annhaliszt@yahoo.com">annhaliszt@yahoo.com</a></p><p>I’m also looking for early adopters. Owners or management heads of an SMB (Small or Medium Business) who would like to test run Ann Haliszt for a significant discount before we go public. My assumption (based on feedback from some testers) is that you are not a finance professional so you don’t have data analysis skills, but you do have data you’d like to dig into to help inform your business decisions.</p><p>An example output of Ann Haliszt is the screenshot below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52LaOafT2LK4wu2SaN_1lQ.png" /></figure><p>I’d be very happy to hear from you, your feedback could make this a more awesome tool for you and thousands like you. Please give me a shout at <a href="/service/mailto:annhaliszt@yahoo.com">annhaliszt@yahoo.com</a></p><p>Do you need a highly skilled developer to help you translate your genAI idea into a product or service? I’m available to work in a consulting or development role — please give me a shout at <a href="/service/mailto:oakingoundeji@gmail.com">oakingoundeji@gmail.com</a></p><p>Thanks all, stay tuned for the next article in the series 🙌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a270cf05da17" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a Python desktop app with pywebview and Flask]]></title>
            <link>https://medium.com/@nohkachi/how-to-build-a-python-desktop-app-with-pywebview-and-flask-73025115e061?source=rss-1b66a948a46b------2</link>
            <guid isPermaLink="false">https://medium.com/p/73025115e061</guid>
            <category><![CDATA[entrepreneurship]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[data-analysis]]></category>
            <category><![CDATA[genai]]></category>
            <category><![CDATA[business]]></category>
            <dc:creator><![CDATA[muyiwa akin-ogundeji]]></dc:creator>
            <pubDate>Tue, 28 Jan 2025 08:18:56 GMT</pubDate>
            <atom:updated>2025-02-11T08:54:52.191Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Those familiar with my work know I typically produce articles around nodejs/javascript, so you may be surprised to see me writing about Python. Bear with me guys, you&#39;ll enjoy this, I promise.</p><p>This article will be part of a 3-part series that explains how to create a Python desktop app using pywebview and flask, how to package it in a cross-platform manner (<a href="https://medium.com/@nohkachi/how-to-package-a-python-desktop-app-for-windows-with-briefcase-a270cf05da17">part 2</a>), and concludes by introducing a genAI app that I built using the things I&#39;ll be sharing (<a href="https://medium.com/@nohkachi/introducing-ann-haliszt-a-genai-bi-tool-for-smb-owners-cd4e129d678a">part 3</a>).</p><h3>Why Python?</h3><p>I sincerely believe that Python is the best tool for building data/ML/AI/LLM apps. While I&#39;d prefer nodejs (because of my expertise and experience with it), Python is simply superior for these use cases.</p><h3>Why a desktop app?</h3><p>LLMs are here to stay! They&#39;re a game changer in many problem domains, the sooner we embrace them, the better. I wrote an <a href="https://medium.com/@nohkachi/understanding-genai-a-practical-guide-for-reasoning-about-llms-and-their-applications-14ce9d4e26af">article</a> where I shared my thoughts about LLMs and genAI.</p><p>With that said, no one wants to expose their confidential data to LLMs and their platform providers. Multiple articles have shared findings about data leaks by ChatGPT an example is this <a href="https://www.zdnet.com/article/chatgpt-can-leak-source-data-violate-privacy-says-googles-deepmind/">one</a>. For this reason, as much as people would love to use LLMs, they&#39;re skittish about exposing their confidential data.</p><p><em>This is where desktop apps come in.</em></p><p>Desktop apps make it possible for an isolated Python environment to be set up on your laptop/desktop, and to have your private data kept private by not being shared with the LLM while the LLM is leveraged to give you insight into this data.</p><p>This is exactly what has been done with <strong>Ann Haliszt </strong>(pronounced analyst 😋), it&#39;s a genAI BI tool targeted at non-financial leaders in the SMB space. The idea is that these leaders (owners, managers, etc.) would like to query the data they have using natural English, but they don’t have data analysis skills and may not have access to a highly skilled data analyst on staff. Ann Haliszt allows these people (and anyone else TBH) with data in the form of csv or Excel files to ask questions about the data using plain English and get high-quality answers as text or charts.</p><h3>About Pywebview</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*j50-2HzvboxWJHqIJewYaA.png" /><figcaption>pywebview logo</figcaption></figure><p><a href="https://pywebview.flowrl.com/">pywebview</a> is a lightweight cross-platform wrapper around a web view component that allows it to display HTML content in its own <em>native GUI</em> window. It gives you the power of web technologies in your desktop application, hiding the fact that GUI is browser-based. You can use pywebview either with a lightweight web framework like Flask (opens a new window) or on its own with a two-way bridge between Python and DOM.</p><p>pywebview IMO is a fantastic tool for building awesome desktop apps around the Python stack. I chose pywebview as my go-to because I wanted the flexibility to build the UI as Isaw fit (instead of being constrained by some GUI kit like QT, Toga, Flet, or Tauri) while being able to take advantage of Python and Python SDKs for AI/ML/LLM apps.</p><h3>Backstory</h3><p>When I started the journey with Ann Haliszt, I initially tried to use Streamlit to build the app. Streamlit worked well in the initial stages, but as the app became more complex, Streamlit quickly fell. Because I had to use a Python-based server to execute code within a Python environment, I next tried Flet. Flet worked (although I was constrained about how the UI was to be structured), nevertheless, I got something working functionally. The trouble started when I tried to package the app for Windows. <em>I wasted tens of hours trying to get it to work, then decided to move on </em>😓<em>.</em></p><p>I took a brief look at Tauri, but TBH, I just didn&#39;t have it in me to learn another GUI toolkit. Then I remembered Electron.</p><blockquote>What would happen if I took all the Python bits from the Flet app, converted it into a Flask app, then used Electron to connect the Flask backend to a custom Ui built with svelte?</blockquote><p>What I found out is that it wouldn&#39;t work well!</p><p>I wasn&#39;t able to sync the startup and shutdown of the Flask server with the UI. I wanted the UI to render only after the server had spun up. Bummer ☹️!</p><p>I looked at Eel — no joy. That&#39;s when I finally discovered pywebview — hallelujah 🥳!</p><p>However, since I&#39;d created a separate UI from the Flask server, I needed a way to use pywebview to connect both, it was not obvious from the pywebview docs, neither did I find helpful info only. I turned to LLMs and believe me it took days to finally work things out.</p><p>After getting this method up and running, the next approach I tried was to serve the UI from Flask, this also worked very well. So in this article, I&#39;m going to share both approaches so you&#39;re free to choose the one you prefer — let&#39;s get into it.</p><h3>Method 1 — Pywebview, separate Flask server, separate UI</h3><p>This method runs the UI and the Flask server in separate threads and coordinates the startup sequence through pywebview. The directory structure is below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*6YyX4ggvIaDUBOKgYpSywA.png" /><figcaption>directory structure for method 1</figcaption></figure><p>The repo for this method is <a href="https://github.com/oakinogundeji/pywebview_flaskBE_separateUI">here</a>. Let us dive in</p><p><em>app.py</em> is the pywebview entry point script. Notice that the <em>be</em> directory and the <em>ui</em> directory are on the same level as the entry point script, this is important.</p><p>Let&#39;s review the pywebview entry point <em>app.py</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0387aadfb5b7d57d09ff25904c127ad2/href">https://medium.com/media/0387aadfb5b7d57d09ff25904c127ad2/href</a></iframe><p>The first 5 lines are imports to set up the script. <em>line 5</em> imports critical methods from the flask app, we&#39;ll review these in a bit.</p><p>Notice that the <em>start_flask</em> function takes a <em>ready_event</em> argument. This is what allows pywebview to ensure that the UI will only be rendered after the server is up and running.</p><p>The <em>startUp</em> function from the Flask app is where any housekeeping is done in the Flask app, the <em>create_app</em> function is responsible for instantiating the Flask app. Note that we wrap the definitions within the <em>start_flask</em> function with a <em>try/except</em> block to grab any startup errors.</p><p>Within the <em>main</em> function, notice the <em>backend_ready</em> event that we create. This is what is passed as the argument to the <em>start_flask</em> function. Notice how this is set up on <em>line 28</em>. <em>Line 29</em> allows us to convert the Flask app into a daemon and <em>line 30</em> starts the Flask app. <em>Line 34</em> is what enforces the waiting for the Flask app to be up and running before spinning up the UI.</p><p>The next interesting section is the logic block between <em>lines 38 and 43</em>. Here we do something that&#39;s required for a cross-platform app. <em>sys._MEIPASS</em> is a special variable that is only defined when the Python application is packaged into a standalone executable using tools like PyInstaller. This is important to ensure that paths to resources (in this case the <em>ui</em> directory) work as expected. We therefore use this logic block to ensure that the app works the same in dev and production (after packaging).</p><p>On <em>line 45</em>, we use the logic block to construct the correct path to the svelte UI, after which <em>lines 51</em> and <em>52</em> create the UI window (also specifying the dimensions and title bar) and start the UI.</p><h4>Svelte UI</h4><p>The code within the <em>ui</em> directory is the output of running the build step for a Svelte app. I simply copied the files/folders in the <em>dist</em> directory and dropped them here. Nothing much to be said here.</p><h4>Flask server</h4><p>This is defined in the <em>be/start.py</em> script. Let us dive in.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5fd8e1d4859e4a463d1923ba03d43fa7/href">https://medium.com/media/5fd8e1d4859e4a463d1923ba03d43fa7/href</a></iframe><p>No biggie happening here TBH, however, we can see some good patterns to adopt for this use case. The <em>startUp</em> function performs housekeeping, while the <em>create_app</em> function preps the Flask app by instantiating it, performing some config, and returning the app object.</p><p>Let us understand this a little more.</p><p><em>line 10</em> instantiates the Flask app by passing the special <em>__name__</em> variable, this is a special variable in Python that represents the name of the current module. The effect is that it allows the Flask app to automatically determine the location of templates, static files, and other resources relative to the current file — very neat stuff 🙌.</p><p><em>line 11</em> configures the <em>secret_key</em> flag for a Flask app. This is critical for things like security, particularly for enabling features like session management and CSRF protection. By using this value <em>b’_5#y2L”F4Q8z\n\xec]/’</em> or something like that we say that the <em>secret_key</em> is a <strong>byte string</strong>, which is recommended for security purposes.</p><p><em>line 12</em> enables Cross-Origin Resource Sharing (CORS) for the Flask app, this allows web apps running on different domains to interact with each other. For example, it allows a web app running on <em>example.com</em> to consume APIs running on <em>api.example.com</em>.</p><p>After this config, the Flask object is ready for use and returned.</p><h4>Test drive</h4><p>When the pywebview app is spun up pay attention to the terminal output and how the UI is spun up only after the Flask app has started.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gK8_Rl_bto3l5mOA4HQ0BA.png" /><figcaption>pywebview terminal output</figcaption></figure><p><em>At this point, I have to share some deeper details about pywebview.</em></p><p>As I mentioned earlier, pywebview is a fantastic tool for building awesome desktop apps around the Python stack. It does this by using different <a href="https://pywebview.flowrl.com/guide/web_engine.html#web-engine">rendering engines</a> on different systems. On Linux, it uses either GTK or QT (I&#39;m not saying more than this — it&#39;s above my pay grade 🤪).</p><p>I explain a little more in the README why I prefer QT to GTK, but for our purposes, the error you see is because we&#39;re using QT and not including any libraries (system level or project level) for GTK. It has no impact on the app, but it&#39;s good for you to understand what&#39;s happening here.</p><p>If you run the code from the repo, and follow the instructions in the README, then you should see a window like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NcP_4WRmdpoIXzLx_zmv5g.png" /><figcaption>Ann Haliszt UI</figcaption></figure><p>That&#39;s all for Method 1. I believe this is a good starter for your projects if you prefer this method.</p><h3>Method 2— Pywebview, Flask server serving the UI on root endpoint</h3><p>This method spins up a Flask server which serves a UI on the root endpoint, pywebview is used to create a GUI that auto opens the root endpoint of the Flask app. The directory structure is below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*BxFVm3jt0A7hMOdZpB_jzg.png" /></figure><p>The repo for this method is <a href="https://github.com/oakinogundeji/pywebview_flask_serving_UI">here</a>. Let us dive in</p><p>Notice that this directory structure is different from the previous method. The <em>be</em> directory is on the same level as the <em>app.py</em> entry point script. Furthermore, there are 2 subdirectories on <em>be</em>, <em>ui</em> and <em>templates</em>. The Flask convention to serve a UI requires that the HTML be within a separate directory (<em>template</em>) from the static assets (.js, .css etc). For the peculiar circumstances of this particular app, the static assets are further encapsulated within an <em>assets</em> sub-directory of the <em>be/ui</em> directory.</p><p>Let’s review the pywebview entry point <em>app.py</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61a816b787236691b7f3a046a7568022/href">https://medium.com/media/61a816b787236691b7f3a046a7568022/href</a></iframe><p>The first 4 lines import dependencies. The <em>start_flask</em> function for this version does not accept any arguments, this is because we don&#39;t need to coordinate a separate UI thread from the Flask server thread on pywebview. I believe the workings of function are clear to us from the explanations given for Method 1.</p><p>Next is the <em>main</em> function, which is also different from the previous version because all it does is spin up the Flask server on a thread before rendering the UI. Nevertheless, there are a few interesting things here.</p><p>On <em>line 25</em>, we see a pywebview directive which sets the value for a setting.</p><p>Finally understanding what this setting did took me days of <strong>heartache</strong>, it&#39;s non-obvious. The basic version of Ann Haliszt allows the user to request a summary of the chat session, this summary is provided as a response displayed on the UI but also as a downloadable TXT file.</p><p>It <em>worked</em> in dev, it <em>worked</em> when I used the packaging tool to test (briefcase, I&#39;ll go into this in-depth in the next article), then it <em>failed</em> to work after packaging. I read the Flask docs, I read the Svelte docs, I thought I&#39;d thoroughly read the pywebview docs, and I used 4 different LLMs (chatGPT, Gemini, Claude, and Mistral&#39;s Le Chat) — no joy 😭!</p><p>I was going crazy, I started questioning everything, didn&#39;t I know how to code? What was I doing wrong? And then, when I returned to the pywebview docs, I saw this setting <a href="https://pywebview.flowrl.com/guide/api.html#webview-settings">here</a> — file downloads on the rendered UI is disabled by default!</p><p>What a relief, but TBH I think it was unnecessary pain, it&#39;s not at all obvious that this is not enabled by default and it was a pain to discover, anyways, this is the directive that must be set if you require your UI to support downloads of files from the server.</p><p><em>line 26</em> is also something we haven&#39;t seen previously. What&#39;s happening here is that we&#39;re directing pywebview to connect the UI that it renders to a URL that we provide. This is the root URL of the Flask app i.e. <a href="http://localhost:8080/"><em>http://localhost:8080</em></a> after this, we start the UI.</p><p>The terminal output and the rendered UI are the same as for Method 1.</p><h4>Flask server</h4><p>This is defined in the <em>be/start.py</em> script. Let us dive in.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5ee64c110c59cbd80b6742c8c636b78/href">https://medium.com/media/c5ee64c110c59cbd80b6742c8c636b78/href</a></iframe><p>The module dependencies are different from Method 1, notice the <em>send_from_directory</em>, and <em>render_template</em> imports that we now require. A quick overview of these methods follows:</p><p><em>send_from_directory</em>: This method is used to serve static files (like images, CSS, JavaScript, etc.) directly from a specified directory within the Flask app.</p><p><em>render_template: </em>This method is used to render HTML templates and dynamically hydrate them with data.</p><p>We already understand the <em>flask_cors</em> dependency and the purpose of the <em>startUp</em> so we&#39;ll skip those.</p><p>The <em>create_app</em> function is different from the previous version. <em>line 15</em> is where we define the path to the directory that holds the static assets for the UI that the Flask server will render.</p><p>In <em>line 16</em>, we instantiate the Flask app as previously described, but we also bind the <em>static_folder</em> key to the path we defined earlier.</p><p><em>line 21</em> is a Flask convention decorator which essentially says that for the &quot;/&quot; route, the function immediately following i.e. <em>line 22</em> is the route handler, what this handler does is render the HTML file which resides in the <em>templates</em> directory.</p><p><em>line 25</em> is another decorator, it tells Flask that the immediately following function should be associated with any URL that matches the pattern<em> </em><strong><em>/</em></strong><em> followed by any path</em>.</p><p>The <em>&lt;path:path&gt;</em> is a variable rule. It means that any part of the URL after the initial <strong>/</strong> will be captured and stored in the variable <em>path</em>. So for us, <em>line 27</em> will use the <em>send_from_directory</em> method to send the file from the <em>static_dir</em> we defined on the Flask app which corresponds to the <em>path</em>. Since we defined <em>static_dir</em> as <em>ui/assets</em>, then when the HTML file requires the <em>index-80ITT_Xu.js</em> file (for example), this function will grab it from the <em>ui/assets/index-80ITT_Xu.js</em> path.</p><h3>Wrapping up</h3><p>Whew, thanks for reading 🥳 — I appreciate the attention you&#39;ve spared. In this article, we&#39;ve reviewed 2 methods for creating a desktop app with pywebview, Flask, and a custom UI. I truly believe that this stack will provide the greatest flexibility and power to develop genAI-based apps that we can deliver to customers or users.</p><p>The next article will deep dive into how we can use Briefcase to package the app we build for multiple platforms including Windows OS and mobile platforms.</p><h3>Help needed</h3><p>I&#39;d like to build a sleeker and more attractive UI, unfortunately for me, it&#39;s beyond my skills. I&#39;d be grateful to anyone who&#39;d like to collaborate with me on this. Svelte skills would be preferred so you can understand what I&#39;ve done already. Please give me a shout at <a href="/service/mailto:annhaliszt@yahoo.com">annhaliszt@yahoo.com</a></p><p>I&#39;m also looking for early adopters. Owners or management heads of an SMB (Small or Medium Business) who would like to test run Ann Haliszt for a significant discount before we go public. My assumption (based on feedback from some testers) is that you are not a finance professional so you don&#39;t have data analysis skills, but you do have data you&#39;d like to dig into to help inform your business decisions.</p><p>An example output of Ann Haliszt is the screenshot below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*52LaOafT2LK4wu2SaN_1lQ.png" /></figure><p>I&#39;d be very happy to hear from you, your feedback could make this a more awesome tool for you and thousands like you. Please give me a shout at <a href="/service/mailto:annhaliszt@yahoo.com">annhaliszt@yahoo.com</a></p><p>Do you need a highly skilled developer to help you translate your genAI idea into a product or service? I&#39;m available to work in a consulting or development role — please give me a shout at <a href="/service/mailto:oakingoundeji@gmail.com">oakingoundeji@gmail.com</a></p><p>Thanks all, stay tuned for the next article in the series 🙌</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73025115e061" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding genAI — A practical guide for reasoning about LLMs and their applications]]></title>
            <link>https://medium.com/@nohkachi/understanding-genai-a-practical-guide-for-reasoning-about-llms-and-their-applications-14ce9d4e26af?source=rss-1b66a948a46b------2</link>
            <guid isPermaLink="false">https://medium.com/p/14ce9d4e26af</guid>
            <dc:creator><![CDATA[muyiwa akin-ogundeji]]></dc:creator>
            <pubDate>Mon, 02 Sep 2024 12:04:23 GMT</pubDate>
            <atom:updated>2024-09-02T12:04:23.375Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding genAI — A practical guide for reasoning about LLMs and their applications</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UNZ10gO8XnQ1eLsvRgjPPQ.jpeg" /><figcaption>The path to understanding LLMs</figcaption></figure><p>My purpose for this article is to share my understanding of the amazing world of genAI. There&#39;s massive hype out there, there&#39;s also loads of confusion and uncertainty. I intend to share what I&#39;ve learned over the past 13 months and lay the foundation for sharing a mental model I call the 7 Factors Framework (next article). Let&#39;s dive in!</p><h3><strong>Overview of genAI:</strong></h3><p>Generative AI (genAI) is the application of a particular type of Neural Network e.g. Large Language Model (LLM) to a wide range of downstream Natural Language Processing (NLP) tasks that involve the creation (i.e. generation) of new content from preexisting data.</p><h3><strong>What are LLMs and what is NLP?</strong></h3><p>NLP is a method of using software models (Neural Networks) to understand and work with human language. LLMs are neural networks trained against a massive corpus of text data and tuned to solve downstream NLP tasks. Downstream NLP tasks are things like Text Classification, Named Entity Recognition, Question Answering, etc. Before LLMs, there were other methods for solving these downstream NLP tasks, such as using traditional ML methods like Ensemble models or using rules-based systems. LLMs excel at downstream NLP tasks, they are more flexible, efficient, and accurate than traditional methods.</p><h3><strong>2 types of genAI models:</strong></h3><p>Recall that genAI models are designed to generate new content from pre-existing data. There are 2 model types that have become the go-to for genAI applications — <em>Diffusion</em> and <em>Transformer</em> models.</p><p><strong>Diffusion models</strong> excel at Image processing tasks. TBH, I haven&#39;t used them much since Image processing is not a biggie in the domains I have experience with.</p><p><strong>Transformer models</strong> are what we see when we think of LLMs.</p><h3><strong>What are Transformers?:</strong></h3><p>A Transformer is a specific type of LLM architecture universally applicable to downstream NLP tasks. Transformers excel at text-based NLP tasks. The generic Transformer uses 2 processing blocks — an encoder and a decoder.</p><p>In layman&#39;s terms, the purpose of the encoder block is to fully understand the input data and to derive meaningful representations that capture the context and relationships between the parts of this data.</p><p>The purpose of the decoder block is to receive encoded input and then generate new content that satisfies the conditions of the overarching task.</p><h3><strong>Types of Transformers:</strong></h3><p>There are 3 types of Transformers based on the types of processing blocks that are used.</p><blockquote>When we understand the processing blocks used, we are more able to effectively use the LLM in our genAI applications.</blockquote><p>The 3 types of Transformers are Encoder-Decoder (E-D), Encoder only (E-O), and Decoder only (D-O) models.</p><h3><strong>E-D:</strong></h3><p>E-D Transformers follow the original Transformer model architecture. They treat all NLP tasks as a text-to-text problem. The current State of the art (SotA) E-D model is T5.</p><h3><strong>E-O:</strong></h3><p>E-O Transformers omit the Decoder block, they use bi-directional processes to gain complete insight into the input data. E-O transformers excel at discriminatory NLP tasks e.g. classification, summary, NER. The current SotA E-O model is BERT.</p><h3><strong>D-O:</strong></h3><p>D-O Transformers omit the Encoder block, they use uni-directional, left-to-right auto-regressive (<em>assuming that the value of a variable at this moment is based on its past values</em>) mechanisms to predict the next token given some input data.</p><blockquote>D-O transformers excel at generative NLP tasks.</blockquote><p>When one thinks of genAI, the typically used models are D-O transformers. The current SotA D-O model is the GPT-4 family.</p><h3><strong>The training process:</strong></h3><p>What makes LLMs so awesome is the training process they undergo.</p><p>The LLMs we use (whether open or closed source) are all the products of a systematic training process that turns a basic LLM into an awesome model that we can use for our own applications.</p><p>Since we&#39;re interested in genAI, we will focus on DO type Transformers moving forward.</p><p>There are 2 main training phases (<em>Pre Training</em> and <em>Alignment</em>) and an optional <em>Fine Tuning</em> phase.</p><h3><strong>Pre-Training (PT):</strong></h3><p>The purpose of PT is to teach the LLM how to infer the next token when primed with some input data. It involves feeding the LLM with a massive amount of data and employing a technique called self-supervised pertaining.</p><p>The main idea is simply, to be able to accurately generate the most statically probable next token when given a random input sequence.</p><blockquote>It is PT that allows LLMs to develop their amazing understanding of human language.</blockquote><p>It is PT that grants LLMs the data they memorize in the form of weights. PT is what concretizes the next token prediction ability of the LLM (DO type Transformers). <strong><em>PT is the phase in which the vast majority of the knowledge that an LLM internalizes is set in stone.</em></strong></p><h3><strong>Alignment:</strong></h3><p>After PT, the LLM is able to successfully generate tokens when primed with some input data. However, the output data can be thought of as gibberish — it is statistically accurate but useless for any end-user application.</p><p><em>The purpose of Alignment is to teach the LLM how to generate useful output data which satisfies the requirements which a user provides to the LLM.</em></p><p>It is the Alignment process that teaches the LLM to follow user instructions, obey prompt constraints, avoid harmful outputs etc. Alignment does not teach the LLM new data, it simply trains the LLM how to generate useful output when primed with some input data.</p><h3><strong>Finetuning (FT):</strong></h3><p>Since LLMs internalize the vast majority of their data during the PT phase, and the data used during the PT phase is typically a massive dataset curated from public data sources, the LLMs lack domain-specific data suitable for organizational or personal applications.</p><p>Finetuning (further training of the LLM on a smaller custom-curated dataset) is used to supplement the LLM&#39;s internalized data with proprietary data acquired from the organization or a person.</p><p>It&#39;s important to understand that FT does not mean that the LLM is automatically going to always refer to your custom data when generating output, what FT does is supplement the LLM&#39;s data with your custom data, and this means that depending on the prompt passed into the LLM, your data may not be referenced at all. We&#39;ll discuss the importance of prompt engineering (PE) shortly.</p><h3><strong>Emergent Capabilities (EC):</strong></h3><p>During Alignment, LLMs are typically tuned towards certain desirable goals e.g. Question Answering, Code generation, avoiding harmful outputs, etc.</p><p>Over time, an amazing phenomenon was observed, as LLMs were scaled in size and were trained on vastly increasing datasets, certain unplanned capabilities began to emerge.</p><p>These capabilities were not specifically trained for but emerged almost as a side effect of scale and data.</p><p>These ECs catapulted the capabilities of LLMs into another realm. The top ECs are: <em>In Context Learning</em> (ICL), <em>Common Sense Reasoning</em> (CSR), and <em>Meta-Learning</em>.</p><p>ICL is what makes prompt engineering a powerful tool for building genAI applications. ICL is the foundation on which RAG (Retrieval Augmented Generation) is built. ICL is why Fine Tuning is not necessary for integrating LLMs into custom datasets driven genAI products.</p><p>CSR is what allows LLMs to more accurately understand the intent of a user when fed a prompt, and to be able to identify the correct data pathways across its internalized memory to generate the desired output data. <em>CSR and ICL work very well together for many genAI tasks.</em></p><p>Meta-Learning makes it possible for LLMs to quickly and efficiently learn and excel at new, previously unseen tasks even when trained against limited data. This is what makes Fine Tuning LLMs against a custom dataset a viable exercise.</p><h3><strong>The Hallucination problem:</strong></h3><p>You&#39;ve probably heard that LLMs cannot be trusted because they hallucinate. Hallucination is defined as LLMs generating untrue data as part of the output.</p><p>In actuality, the whole concept of hallucination as applied to LLMs is a misnomer.</p><p>LLMs do not hallucinate, what they do is generate data for which they have predicted the next token based on:</p><ol><li>The training data they were exposed to</li><li>The Alignment with which they were tuned, and</li><li>The emergent capabilities (ICL/CSR) that they possess.</li></ol><blockquote>So, when an LLM hallucinates, our takeaway must be that we have not primed it with the proper data to leverage ICL i.e. our prompt engineering is faulty, or the base LLM itself may be less capable than desired i.e. it may not be at the proper scale to benefit from Emergent Capabilities or it may be improperly trained during the PT phase.</blockquote><p>Long story short, there&#39;s no such thing as hallucination as applied to LLMs, what we think of as hallucination is actually an integral feature of LLMs which makes them suitable for genAI tasks.</p><h3><strong>How to reason about LLMs and our genAI use cases:</strong></h3><p>LLMs are amazing, they make it possible to build apps that democratize the understanding of data, integrate &quot;<em>intelligence</em>&quot; into business workflows/processes, and allow the creation of all kinds of agents and assistants.</p><p>When we clearly understand what LLMs are and the types of LLMs used for genAI tasks, then we can effectively integrate LLMs into our projects and leverage them to enhance our capabilities to achieve business objectives.</p><p>So, how should we reason about LLMs? I&#39;ve conceived of what I call the <em>7 Factors framework</em>, I will share the details in the next article, but in a nutshell, the way to reason about LLMs is to aim to integrate an LLM as the brain of our genAI apps such that we can leverage its emergent capabilities to accurately reason about the tasks we provide it, properly leverage our custom data or supplementary data from tools we provide it, make correct routing decisions about processes or paths, and generate useful data that we can use to gain a competitive edge.</p><h3><strong>The importance of Prompt Engineering (PE) for practical genAI applications:</strong></h3><p>Prompt Engineering is both an art and a science.</p><p>PE helps us craft the proper prompts to prime LLMs so they can generate our desired output based on the input data we provide.</p><blockquote>PE requires that we clearly understand the capabilities and limitations LLMs so we can effectively create input data that triggers LLMs to generate the most relevant and helpful responses.</blockquote><p>When we consider the power of ECs like ICL and CSR, we see that the proper input (i.e. prompt) can cut down on the back-and-forth typically encountered when we naively interact with LLMs.</p><p>An example scenario. Let&#39;s say we want to build a BI/Data Analysis tool using LLMs to allow questions to be asked of our data using natural language. We would typically already have some tools we are comfortable with e.g. Pandas, Matplotlib, etc.</p><p>A naive solution would simply ask the LLM a question and leave the LLM to try to generate the code that will be run to provide an answer. This approach is why many tools provide less than optimal responses leading to great frustration.</p><p>A PE-driven approach would include dynamically populated code snippets which include the proper paths to the data, the correctly installed libraries, etc, also, data like example pairs of input questions matched to correctly generated output code to serve as guidance for the LLM. <em>This approach can take the accuracy of the genAI app from less than 40% to over 80% — this is a significant increase in capability.</em></p><p>So, long story short, PE is vital for developing genAI apps since the underlying LLMs will almost always be DO-type Transformers. Building high-quality PE skills is a difference maker.</p><h3><strong>Conclusion:</strong></h3><p>GenAI is a game changer for developing transformative applications that can give us a competitive edge. In order to take full advantage of the power of genAI, we must cut through the fog of confusion, misunderstanding, and misinformation to acquire a clear mental model that helps us make sense of this powerful technology.</p><p>I&#39;m not an AI researcher or scientist, but as a software engineer, my interest is establishing accurate working knowledge that helps me deliver value for clients on their genAI projects. I trust you&#39;ve benefitted from this article. I look forward to your comments.</p><p><em>Are you looking for a top-notch engineer for your genAI project? would you like some unbiased advice and consulting? connect with me at teliosng@gmail.com</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14ce9d4e26af" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Guess who's back…?]]></title>
            <link>https://medium.com/@nohkachi/guess-whos-back-d48778e84d88?source=rss-1b66a948a46b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d48778e84d88</guid>
            <dc:creator><![CDATA[muyiwa akin-ogundeji]]></dc:creator>
            <pubDate>Thu, 22 Aug 2024 11:44:05 GMT</pubDate>
            <atom:updated>2024-08-22T11:44:05.120Z</atom:updated>
            <content:encoded><![CDATA[<p>October 26, 2016.</p><p>Almost eight years since my last article. I look back, and the changes in my life are almost unbelievable. The more I waited for the right things to say, the harder it was to say anything. I really enjoyed sharing with you all, yet the longer time went by without my sharing, the harder it became to share — life intruded.</p><p>This isn&#39;t a planned article or anything like that, I&#39;m just going to pour out some thoughts as I prep to get back in the saddle.</p><p>I would like to thank everyone who has followed me since I started writing and sharing. I have been encouraged to see that my work has benefitted people, even though I haven&#39;t written in almost eight years, my heart has been warmed continually as I see the weekly reports from Medium about people reading and viewing my articles.</p><p>I want to thank all of you, I wrote these articles for you and me, and I&#39;m grateful for your support over the years. I&#39;ve met some of you and a few have become like family. I&#39;ve heard from some of you about how my work has helped you — thank you for the encouragement.</p><p>So what happened?</p><p>I started a software dev team, we did good work but I lacked the business skills to keep us running after the project we were working on came to an end. It was tough to realize this lack on my part. I had to learn the lesson that tech skills don&#39;t translate to business skills. I learned about people, and I learned about myself, it was humbling.</p><p>I had to go back to work as a freelance dev. The main reason I was able to get back up to speed was because I had my articles to refer to. That&#39;s when I truly realized the value of writing the way I do. Again, I&#39;m grateful to all of you who inspired me to write in the early days, thanks once again.</p><p>One of the most important skills we can acquire is the ability to learn. Wisdom comes with time and experience, but learning keeps us continually relevant. I&#39;ve expanded from skillset from just being a nodejs backend developer, I&#39;ve grafted on Cloud engineering, DevOps, Solutions Architecture, and Business Analysis. I&#39;ve learned from my failings and the wisdom of others.</p><p>I&#39;ve become quite competent with Python and drank deep at the fount of LLMs. I&#39;ve developed my mental model to reason about gen AI systems and worked on my gen AI project.</p><p>Above all, I&#39;ve learned to put my trust in God, it&#39;s humbling to realize how many things I have no control over, how much I rely on God&#39;s Mercy to provide for my family, to meet my obligations, to keep me and mine safe in a crazy world, to have Hope when all seems lost. HUMILITY is the greatest lesson I&#39;ve learned since October 26, 2016.</p><p>Thank you all again, my writing is nothing without your support, I plan to write regularly once again. I will share my experience in workflow automation, DevOps, and cloud engineering. I will share my thoughts on my new area of focus — LLMs and gen AI. I will answer any questions you have and work with you on projects for our mutual learning.</p><p>Stay tuned guys — Guess who&#39;s back!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d48778e84d88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Learn the language…. Stop blaming Javascript!!!]]></title>
            <link>https://medium.com/@nohkachi/learn-the-language-stop-blaming-javascript-8c62ed428143?source=rss-1b66a948a46b------2</link>
            <guid isPermaLink="false">https://medium.com/p/8c62ed428143</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[muyiwa akin-ogundeji]]></dc:creator>
            <pubDate>Wed, 26 Oct 2016 09:21:52 GMT</pubDate>
            <atom:updated>2016-10-26T09:21:52.043Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently read <a href="https://hackernoon.com/why-you-shouldnt-use-var-anymore-f109a58b9b70#.6o1yd1fuu">this article</a> and my soul was grieved. Let me start by saying i don’t know who <a href="https://hackernoon.com/@markbrouch">Mark</a> is, and i do respect him for the position he has achieved as a Senior Developer but i’m grieved and saddened by the advice contained in his article.</p><p>I also don’t know <a href="https://medium.com/@caerphoto/honestly-this-problem-wouldnt-be-nearly-so-bad-if-people-were-taught-to-write-javascript-properly-196f6100885e#.xav2kzt6s">Andy</a> but i really applaud him for the response he made. The thrust of this article will be to explain why it’s totally necessary for any Javascript developer at whatever skill level to have at least a basic mastery of the main tool used — the Javascript Language (or ECMAScript if you prefer).</p><h4>Understanding the Javascript Engine</h4><p>A common assumption is that Javascript is an interpreted language like Bash. This is a fallacy. The Javascript engine actually uses a very smart JIT Compiler which performs 2 passes over the code. The first pass scans the code and is responsible for assigning memory space to constructs like functions and variable declarations, the second pass runs the code by implementing assignments and executing statements and expressions.</p><p>This 2-pass behavior is what is responsible for the ‘hoisting’ mechanism that Mark (and many others) perceive as a ‘gotcha’.</p><p>Because Javascript originally had only function scoping, when a variable declaration is explicitly made using the ‘var’ keyword (or implicitly by making an assignment), on the first pass the engine recognizes that a variable (which is simply a label/identifier which binds some memory location to the value on the RHS of the assignment operator) has been declared and it sets aside some memory for that variable but it doesn’t yet assign a value to it, thus the value becomes ‘undefined’.</p><p>On the second pass the engine assigns the value specified by the assignment operator to that variable and life goes on.</p><p>Let’s consider an example.</p><pre>a;// undefined<br>var a = 6;// value assignment <br>a;// 6</pre><p>The above is a simple illustration of what we just discussed. On the first pass the engine recognizes that a variable with the label ‘a’ is being declared, it sets aside memory space for ‘a’ and literally says to itself that it knows that ‘a’ is a variable but the value assigned to a has not yet been defined i.e. ‘undefined.</p><p>Since there’re no more variable declarations, the second pass starts. When it encounters the following statement:</p><pre>a;</pre><p>It knows that ‘a’ is a variable because memory space has been allocated to it, when it checks for the value of the variable what does it find? Of course, it finds ‘undefined’ and so it very correctly returns ‘undefined’ as the result of executing that statement.</p><p>It moves to the next line and sees an assignment operation, it checks if any variable identified by the label ‘a’ exists in memory… what does it find? There is a variable with the label ‘a’, and so it assigns the value identified by the RHS of the assignment operator to that variable i.e. ‘6’.</p><p>Next it encounters the following statement:</p><pre>a;</pre><p>It checks memory for a variable identified by the label ‘a’, it finds that the variable exists, nest it executes the statement and what is the value assigned to the variable? Now the value is ‘6’!</p><p>The preceding is perfectly logical and reasonable behavior. Please let’s understand our tools as we use them.</p><p>Mark uses the following example:</p><pre>var callbacks = [];<br>(function() {<br>  for (var i = 0; i &lt; 5; i++) {<br>    callbacks.push( function() { return i; } );<br>  }<br>})();</pre><pre>console.log(callbacks.map( function(cb) { return cb(); } ));</pre><p>He claims “A novice engineer might answer (incorrectly) that the result is [0, 1, 2, 3, 4], <em>a reasonable analysis, but one that falls victim to the JavaScript “hoisting” gotcha</em>.”</p><p>Deeper examination reveals that this is flawed reasoning, ‘hoisting’ has nothing to do with what’s happening here!</p><p>What is actually happening is how Javascript interprets values! In Javascript, Functions are first class citizens, i.e. they’re values just like numbers or strings. Furthermore, in Javascript, functions are complex values/types just like Objects and Arrays.</p><p>In Javascript, primitive or simple values/types like numbers or strings have their ‘value’ replicated by copying i.e. when a simple value has been assigned to a variable that value can’t be changed e.g.</p><pre>var a = 1;//simple type or value<br>var b = a;//assignment of value by copying<br>a;// 1<br>b;// 1<br>b = 2;<br>b;//2<br>a;//1</pre><p>What we see in the above is that when ‘b’ is assigned a value derived from evaluating ‘a’, any change to variable ‘b’ has no effect on the existing value of ‘a’.</p><p>Compare this to the following:</p><pre>var a = [1, 2, 3, 4];//complex value/type<br>var b = a;// what&#39;s going on here?<br>a;// [1, 2, 3, 4]<br>b;// [1, 2, 3, 4]<br>b.push(5);//mutate the &#39;value&#39; of &#39;b&#39; only!<br>b;// [1, 2, 3, 4, 5]<br>a;// what should we get?</pre><p>What would you expect the value of ‘a’ to be? It turns out that the answer is ‘[1, 2, 3, 4, 5]’! And not ‘[1, 2, 3, 4]’ as may have been expected.</p><p>What’s going on here? Complex values/types in Javascript have their ‘value’s copied/duplicated by ‘reference’! This means that multiple variable bound to the same complex value will refer to the same memory location — any change to one of these variables will mutate the underlying common memory location and affect all variables which refer to it.</p><p>With this background, we can more clearly understand what’s happening in the example Mark uses:</p><pre>callbacks.push( function() { return i; } );</pre><p>Is a complex value! Thus when the iteration completes, the value of the variable identified by ‘i’ becomes ‘5’! And since all the values in the callback array refer to the same underlying value (identified by ‘i’), when execution time comes:</p><pre>console.log(callbacks.map( function(cb) { return cb(); } ));</pre><p>The Javascript engine will ask ‘what is the present value of the variable identified by “i” ?’, the answer is of course ‘5’, and so when it executes each function in the array the answer reflects the common value which they all point to i.e. ‘5’.</p><p>With the introduction of block scoping in Javascript via the ‘let’ and ‘const’ keywords something interesting is possible. If these keywords are used in the following example:</p><pre>var callbacks = [];<br>(function() {<br>  for (<strong>let</strong> i = 0; i &lt; 5; i++) {<br>    callbacks.push( function() { return i; } );<br>  }<br>})();</pre><pre>console.log(callbacks.map( function(cb) { return cb(); } ));</pre><p>What happens is that the block scoping feature creates a unique memory location for the variable ‘i’ for each iteration of the loop and the function referencing this variable correctly retains the proper memory reference via ‘closure’. Thus when execution time occurs, the intuitive result ‘[0, 1, 2, 3, 4]’ is returned.</p><p>I didn’t intend to be so long winded but i was really hurt that a person of Mark’s stature would give the advice he did. Advice like this from respected figures like Mark is one of the reasons Javascript has such a bad rep.</p><p>To paraphrase <a href="https://medium.com/@caerphoto">Andy</a> “… please learn Javascript”, don’t come to this beautiful and expressive language with preconceived notions, please follow people like <a href="https://medium.com/@_ericelliott">Eric Elliot</a> and <a href="https://twitter.com/getify?lang=en">Kyle Simpson</a> … these people grok Javascript!</p><p>But most importantly, take the time to learn Javascript and form your own opinions, don’t let ‘experts’ confuse you by saying ‘var is wrong, or eval is evil or never use ==’.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8c62ed428143" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[THE PRACTICAL GUIDE TO BUILDING DATA DRIVEN WEB APPS WITH VUE.JS]]></title>
            <link>https://medium.com/@nohkachi/the-practical-guide-to-building-data-driven-web-apps-with-vue-js-32bd03c1a5a9?source=rss-1b66a948a46b------2</link>
            <guid isPermaLink="false">https://medium.com/p/32bd03c1a5a9</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[muyiwa akin-ogundeji]]></dc:creator>
            <pubDate>Tue, 05 Apr 2016 13:20:40 GMT</pubDate>
            <atom:updated>2016-04-06T15:02:45.937Z</atom:updated>
            <content:encoded><![CDATA[<p>Vue.js is a javascript library for building data driven applications along the MVVM (Model-View-ViewModel) pattern/architecture. Vue is lightweight, fast and easy to learn, yet like javascript itself, it’s flexible and deceptively powerful in the capabilities it gives us as developers to build reactive, component based, data driven web applications which compare favorably with applications developed with more popular libraries/frameworks such as React, Angular or Ember. A Vue.js app instance is built around the ‘VM’ in the MVVM architecture.</p><p>The code for all apps referenced in this series are available on <a href="https://github.com/oakinogundeji/practical_guide_to_vue.js">github</a>. The initials M, V, and VM will be used throughout this article to reference Model, View and ViewModel respectively.</p><h4>OVERVIEW:</h4><p>In this article series, we will explore the key features of Vue.js and supporting libraries such as vue-resource and vue-router which allow us to build 3 basic types of applications.</p><ol><li>Base VM , multi-component applications: This type of application won’t have AJAX capabilities or routing. e.g. a simple browser based TODO app.</li><li>Base VM, multi-component applications with AJAX capabilities: This is the type of application we have in mind when we say an application is ‘data driven’. This app will query a data store to retrieve data which it will render in the browser e.g. a simple customer management app for a small business.</li><li>Base VM, multi-component applications with AJAX and client-side routing: This is the quintessential SPA. This kind of app leverage’s most of the features of the Vue.js ecosystem and it is the sort of app which we would build for an enterprise, start-up or business to power internal or client facing software. e.g. an order management app with social authentication via OAUTH.</li></ol><p>Let’s get started.</p><h4>THE BASICS:</h4><p>Vue.js as mentioned previously is built on the MVVM principle, thus the 3 major components of a Vue application are the VM, the V and the M.</p><p>The V is simply an HTML template which defines the structure for the app. The V is driven by data bindings and directives which tie the VM to the V.</p><p>The M is simply a Javascript object which holds what we can think of as the ‘working data set’ which the VM requires to power the V and respond to user actions.</p><p>The VM is the heart of a Vue application, it is responsible for formatting the data contained in it’s associated M and feeding that data to it’s associated V in the form of ‘data bindings’, it also responds to user actions on the V by intercepting those user actions through ‘directives’.</p><p>Let’s visualize this interplay with a ‘trivial’ example. You can play with the <a href="http://codepen.io/oakinogundeji/pen/PNpyBX">pen</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*nPPUIp1bhH_eUJv0n3l5Xg.png" /><figcaption>initial state of sample app</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/364/1*4VJggquFVNRe4CdePs4yTQ.png" /><figcaption>app with some data</figcaption></figure><p>The code for this example follows:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/796ff350d0fa0c7f5f749246914b1bf9/href">https://medium.com/media/796ff350d0fa0c7f5f749246914b1bf9/href</a></iframe><p>The first section we’ll examine is the M. Notice lines 28–31, these sections of code define the M for the Vue VM, we notice that it’s a simple javascript object containing 2 properties ‘title’ and ‘user’. Next we examine the VM on lines 32–35, the first thing we notice is that the VM is an ‘instance’ of the ‘Vue’ constructor. For this trivial example, we simply define 2 properties for the options object passed to the VM ‘el’ and ‘data’.</p><p>‘el’ references the HTML element which will be bound to the VM and serve as its V, ‘data’ references the javascript object which will be bound to the VM and serve as its M.</p><p>In this example, ‘el’ is bound to the ‘div’ with ‘id’ of ‘app’ and ‘data’ is bound to the object with identifier ‘model’. <strong>NB</strong> we could have simply defined this inline thus:</p><pre>var app = new Vue({<br>  el: &#39;#app&#39;,<br>  data: {<br>    title: ‘Sample Vue app’,<br>    user: ‘’<br>  }<br>});</pre><p>Now let’s examine the V. Lines 20–24 are the interesting portions for us. Notice line 20 — the ‘div’ bears the ‘id’ of ‘app’. This by far the most important portion of the V — it’s identifier which must be unique and must correspond to whatever value the ‘el’ property of the VM’s options object bears.</p><p>On line 21 we encounter our first data binding, a simple ‘interpolation’ in which we dynamically supply a value for insertion in the HTML. Notice that this value is the value of the ‘title’ property of the M of the VM (line 29).</p><p>On line 22 we encounter our first directive, we ‘2-way bind’ the value of the ‘input’ widget to the value of the ‘user’ property of the M of the VM (line 30). This ‘2-way binding’ ensures that whatever we type into the ‘input’ is set as the value for the ‘user’ property.</p><p>On line 23 we see the result of the application of the ‘2-way binding’. We interpolate the value of the ‘user’ property of the M of the VM into thee HTML. Since this value has been previously ‘2-way bound’ using ‘v-model’ whatever the user types into the ‘input’ widget will be dynamically rendered!</p><p>What we learn from this trivial example is that the data-bindings and directives on the V MUST all be properties of the options object of the VM. This includes ‘methods’ for handling user input the most basic of which is ‘v-model’.</p><p>Now that we have a basic understanding of the dynamics of a Vue application, let’s move on to something more practical (after all this is a practical guide).</p><h4>BASE VM , MULTI-COMPONENT APPLICATIONS:</h4><p>This type of application comes up quite often, we use them for many simple tasks — internal and client facing. A good example is a TODO application. As a ‘non-trivial’ application, it will leverage one of Vue’s most powerful features — components.</p><p>This is what we will be building, you can play with the <a href="http://codepen.io/oakinogundeji/pen/GZWwJe">pen</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*6Sk1CNeQL39u-HmdT6PlLg.png" /><figcaption>initial app state</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*fbSDPrtFe2k48VXSv_PUqw.png" /><figcaption>new Todo created</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*S3i6UTJ4SAl2bU4AtgtK1Q.png" /><figcaption>a Todo has been completed</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*u9I1M659gq8Sb0Z2ECptQg.png" /><figcaption>view all Todos regardless of completion status</figcaption></figure><h4>Directory Structure:</h4><pre>/<br>| - package.json<br>| - index.html<br>| - main.js<br>| - components<br>       | - allTodos<br>              | - index.js<br>              | - template.html<br>       | - completedTodo<br>              | - index.js<br>              | - template.html<br>       | - newTodo<br>              | - index.js<br>              | - template.html<br>       | - uncompletedTodo<br>              | - index.js<br>              | - template.html</pre><p><strong>package.json:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/31f6f648796a7f1205884bfcadb13125/href">https://medium.com/media/31f6f648796a7f1205884bfcadb13125/href</a></iframe><h4>BASE VM:</h4><p>Let’s start our exploration of the capabilities Vue.js gives us by examining the base VM. In this example, the base VM will use the HTML structure as defined in ‘index.html’ as it’s V. Note that the ‘script’ referenced isn’t ‘app.js’ but ‘main.js’, this is because we are using ‘watchify’ as a ‘module bundler/build tool’ during the development of this app.</p><p><strong>Index.html:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/acdcc6b0a3a9b2f86bb651af52c575bc/href">https://medium.com/media/acdcc6b0a3a9b2f86bb651af52c575bc/href</a></iframe><p>Lines 22–33 are the interesting portions of the HTML structure for us. On line 22 we label the HTML element which will serve as the <strong>‘mount point’</strong> for the base VM i.e. the base VM’s ‘el’. This is the ‘div’ with ‘id=”app”’. On line 23 we come across a powerful feature of Vue.js a custom element which defines a <strong>‘component’</strong>. Vue.js components are developed according to the ‘Web Components’ standard and allow us to define custom HTML elements which represents reusable HTML structures in our code (more on that soon).</p><p>By simply examining the component’s name we have a good idea what it represents — new todos!</p><p>Lines 25–30 encompass a group of buttons which represent various actions users can take on the Todo app itself, these actions are made possible by directives e.g. <strong>‘@click.stop.prevent=”viewAllTodos” ‘</strong> which allow the base VM to intercept user activity and act on it based on the handlers which are referenced by the directives. Note that in this instance ‘<strong>@</strong>’ is a shorthand notation for <strong>‘v-on</strong>’ , ‘<strong>.stop</strong>’ and ‘<strong>.prevent</strong>’ are ‘<strong>modifiers</strong>’ which modify the behavior of the event.</p><p>The directive can be interpreted as follows “when there is a click event on this element do the following things 1) ‘stop’ the event from propagating i.e. the ‘.stop’ modifier, 2) ‘prevent’ the default behavior of the event i.e. ‘.prevent’ — in this case, do not navigate away from the page and 3) call the ‘viewAllTodos’ handler (i.e. method) of the base VM.</p><p>NB. The preceding explanation holds true for any V of a Vue.js VM regardless of whether that VM is a ‘base VM’ or a component (more on this soon).</p><p>On line 32 we encounter a special Vue.js element the ‘component’ element. The purpose of this element is to allow a ‘parent’ VM to dynamically render ‘child VMs’ i.e. components which share the same mount point. This allows for different ‘screens’ to be switched without verbose coding. The ‘component’ has 3 attributes which are really important to understand.</p><ol><li><strong>‘:is’</strong> — this special attribute binding is responsible for determining which component is to be dynamically rendered. Notice the full attribute <strong>‘:is=”activeComponent”</strong>. This means that the ‘parent’ component or base VM must have an ‘<strong>activeComponent</strong>’ data property which represents the ‘<strong>child component</strong>’ to be dynamically rendered by some action. The choice of ‘activeComponent’ as the name is purely arbitrary, you can give it whatever name you choose. For the sake of completeness, I should point out that in a recent interaction with <strong>Evan You</strong> (The author of Vue.js) he pointed out to me that ‘component’ could also be used to render a <strong>list</strong> of components for a VM. But the more usual practice is what I’ve described here. For completeness, ‘:is’ is shorthand for ‘<strong>v-bind:is</strong>’ which means that the ‘is’ attribute of the base VM is bound to a specific data property on that same VM (in this case ‘activeComponent’) notice that ‘is’ simply indicates what ‘component’ is to be rendered at that mount point. It is the ‘:is’ <strong>dynamic binding</strong> which makes it possible for child components to be dynamically rendered on the same mount point.</li><li><strong>’keep-alive’</strong> — To avoid continual re-rendering when dynamic components are switched out we use the ‘keep-alive’ attribute to cache the switched out component in memory. This means that the state of the component at the time it is switched out is preserved. This is really useful.</li><li><strong>’:todos-list’</strong> — Vue.js and other reactive libraries e.g. React have the concept of ‘<strong>props</strong>’ — theses are mechanisms which allow a ‘<strong>parent</strong>’ component/VM to pass data from itself to a dependent ‘<strong>child</strong>’ component. In this case the full prop attribute is <strong>‘:todos-list=”todos” ‘</strong>. Because this prop is defined on the ‘components’ tag, we can interpret the intent of this code as follows: The ‘todos-list’ prop of any child component which is dynamically rendered through this mount point receives its value from the ‘todos’ data property of the base VM. <strong>Note</strong> that the ‘prop’ is defined here in ‘<strong>kebab-case</strong>’ i.e. ‘todos-list’ but in the component which will consume the prop, it <strong>MUST</strong> be defined in ‘<strong>camelCase</strong>’ e.g. ‘todosList’ (more on this soon).</li></ol><p>So these three attributes give us powerful capabilities in determining the behavior and capabilities of our dynamically rendered components.</p><p><strong>App.js.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/984dfd033f1a47c69fae9e5b2db1163c/href">https://medium.com/media/984dfd033f1a47c69fae9e5b2db1163c/href</a></iframe><p>app.js holds the code for the base VM. Since we’re using ‘<strong>watchify</strong>’ as our development build tool/module bundler, we can develop this portion of our app using CommonJS style ‘require()’ statements. On line 5, we require our sole module dependency which is ‘vue’. Lines 12–75 hold the body of the base VM which is responsible for tying all the components of this app together.</p><p>On line 12 we instantiate the base VM and pass in an ‘options’ object to the Vue constructor. Let’s examine the constituent properties of this object and understand how they contribute to the overall behavior of the app.</p><p>On line 13, we define the ‘el’ property which serves as the mount point for the VM through which the V will be rendered. On lines 14–17 we define the ‘data model’ property which defines the M from which the VM extracts it’s ‘working data set’. Line 15 defines the ‘todos’ property as an array, recall that this ‘todos’ property provides the value for the ‘todos-list’ prop of the dynamically rendered components which share the ‘component’ mount point.</p><p>Line 16 defines the ‘activeComponent’ property which we notice has a ‘default’ value of ‘app-uncompleted-todo’. If we recollect the explanation of how ‘:is’ works, we realize that the intent here can be expressed as follows: <strong><em>“When the base VM is initially rendered, the child component which should be mounted at the ‘component’ mount point should be the component which corresponds to the ‘app-uncompleted-todo’ component”</em></strong>.</p><p>Note that whereas we defined a dedicated mount point for the ‘app-new-todo’ component (index.html line 23), the other components which are to be dynamically rendered simply share the ‘component’ mount point. If you examine this app with <strong>chrome dev tools</strong>, you would see that what is rendered isn’t ‘app-new-todo’ or ‘components’ but the actual HTML which is referenced by the component (more on this soon).</p><p>Moving forward, the default value of the ‘activeComponent’ property of the base VM (which determines the child component to be dynamically rendered) is ‘<strong>app-uncompleted-todo</strong>’.</p><p>Lines 18–41 define the ‘<strong>methods</strong>’ of the base VM, these methods are essentially DOM event handlers which respond to various events triggered by user action on the V and intercepted by directives e.g. ‘<strong>@click</strong>’, ‘methods’ can also be simply methods i.e. functions of an object which can be invoked to perform certain tasks.</p><p>Lines 19–30 define the <strong>DOM event handlers</strong> which handle the ‘click’ events on the V as defined in index.html (lines 25–30). Taking the first of these as an example (line 19–22) we notice that what the method does is simply to ‘set’ the ‘activeComponent’ property of the base VM to a new value e.g.</p><pre><strong>this.activeComponent = ‘app-all-todos’;</strong></pre><p>which sets ‘activeComponent’ to ‘app-all-todos’ and thus causes the component which is referenced by ‘app-all-todos’ to be rendered on the ‘component’ mount point.</p><p>Lines 31–40 define a ‘method’ which provides some service to the base VM, we will examine this in detail shortly. Lines 42–47 define the ‘components’ of the base VM. Each component is essentially an instance of an extension of the Vue.js constructor.</p><p>Components would normally be created as follows:</p><pre>var component = Vue.extend({…options…});</pre><p>However in this case with the aid of ‘watchify’ we can modularize our application by defining each component in a separate module and then ‘requiring’ the component. Each component as defined in lines 43–46 corresponds to a custom tag e.g. we see how ‘&lt;app-new-todo&gt;’ tag (index.html line 23) is referenced by the component defined on line 43. The other components (lines 44–46) are dynamically rendered and share the ‘component’ mount point (index.html line 32) as explained previously. We will examine each component in detail shortly.</p><p>The next ‘section’ of the base VM options object is the ‘events’ property. This property defines handlers for custom events which are responsible for communications between the base VM and its child components.</p><p>Let’s examine a couple of these custom event handlers. Line 49 defines the ‘newtodo’ event. When this event is emitted, the handler is invoked and passed a ‘todo’ as argument, on line 51 the handler inserts the new ‘todo’ into the ‘todos’ array of the base VM and then the handler does two interesting things: 1) ‘broadcasts’ an event ‘getnewtodo’ along with the todo passed to it as an argument (line 52), ‘broadcasting’ is a Vue.js mechanism for allowing a parent VM/Component to communicate with ‘child’ components and ensure a particular action is effected without the parent directly mutating the child’s state. This is very cool as it allows for loosely coupled components. The interested component(s) which are subscribed to the ‘getnewtodo’ event will handle them when this event is emitted. 2) ‘broadcasts’ another event ‘updatetodos’ (line 53) which will be handled by the components subscribed to that event.</p><p>Line 55 declares the ‘completedtodo’ event and handler. Notice how on line 57, the ‘extractTodo’ method previously defined on lines 31–40 is invoked by the handler and the return value is used on line 58 to change the ‘completed’ value of the ‘todo’ passed to the handler as an argument. The behavior of the remaining handlers can be easily determined by following the line of thought we have just used.</p><p>Having walked through the base VM, let’s examine the components.</p><h4>APP-NEW-TODO:</h4><p>This component is contained within the components/newTodo directory. We notice it consists of two files/modules — index.js and template.html. Evan You prefers single file components i.e. the template and script are contained in the same file. I prefer separation of script from markup since the markup or script can be fairly lengthy and I think it’s cleaner to separate them. So we will adopt my preference :-).</p><p>Let’s begin by examining the V as defined in ‘<strong>template.html</strong>’.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b7b107705c1b945d346c7133c27fcf2/href">https://medium.com/media/5b7b107705c1b945d346c7133c27fcf2/href</a></iframe><p>First let’s recollect that the mount point for this component is defined on line 23 of index.html i.e. ‘&lt;app-new-todo&gt;&lt;/app-new-todo&gt;’, however the actual structure of the component is contained in the ‘template.html’ under consideration.</p><p>The HTML which will be used to render this component is essentially a form with an input widget and 2 button widgets. The input widget is ‘2-way data bound’ to the ‘todo’ property of the component VM (line 5) while the buttons are bound to the ‘addTodo’ and ‘discardTodo’ methods of the component VM lines 10 and 14.</p><p>Moving on, let’s examine the code for the component as contained within <strong>‘index.js</strong>’.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9688203903b1d0ae553aa819430b65ad/href">https://medium.com/media/9688203903b1d0ae553aa819430b65ad/href</a></iframe><p><strong>NB</strong> You may recollect that the use of ‘index.js’ as the default entry point for a module represented by a directory is a common idiom in the Node.js world.</p><p>On line 2 of index.js, we begin by declaring a ‘template’ property and setting it’s value to <strong>“require(‘./template.html’)”</strong>. Let’s discuss 2 things here.</p><ol><li>When a component is declared in Vue.js, one may use either ‘el’ or ‘template’ to reference the HTML element which will serve as the mount point for that component. If ‘el’ is used, then one must set the value of ‘el’ as a function that returns an HTML element. If ‘template’ is used, our intent is that the markup content of the referenced template (either as a string or required as we have done here) will replace the mount point of that component. This is the reason <strong>‘&lt;app-new-todo&gt;&lt;/app-new-todo&gt;’</strong> doesn’t appear in the dev tools. So long story short, it’s simply more straightforward and convenient to use ‘template’ to reference the DOM element through which a component’s V will be rendered.</li><li>The use of “require(‘./template.html’)” allows us to pull in the markup we have built in a separate file thanks to ‘<strong>partialify</strong>’ I think it’s really neat. Moving on.</li></ol><p>Lines 3–7 define the ‘data’ property of this component. Notice that unlike the base VM (lines 14–17 of app.js) the value of this property is a function which returns an object rather than a POJO (plain old javascript object). Why? Recollect that in javascript, the values of objects are passed by reference i.e. a new object is not created thus if the component is used in multiple portions of the app, any change to its state will affect the other copies of that component. However, if an object returned from a function is used as the data property, then each ‘copy’ of the data object is a unique instance and changes to it’s properties do not affect any other copy of that component.</p><p>OK, note that the ‘todo’ property (line 5) is set to a blank string initially, this is appropriate because we intend that the value of this property be determined by user input. This is why we ‘2-way bound’ this ‘todo’ property to the input widget on the template (line 5 of ‘template.html’).</p><p>Lines 9–19 define the ‘addTodo’ method.</p><p>Lets examine this method, after confirming that the click event on the button (line 10 of template.html) occurs when the user has typed something into the input widget (line 10 of index.js), we create a new object to represent the ‘todo’ (lines 11–14) then we clear the input widget by setting the ‘todo’ property to which it is bound to a blank string (line 15) and then the ‘newtodo’ event is emitted with the new ‘todo’ object we created as it’s data (line 16).</p><p>Just as we discovered that ‘this.$broadcast’ is the mechanism by which a parent VM communicates with it’s child components, likewise ‘this.$dispatch’ is how child components communicate with the parent VM. Again this is a great example of loose coupling.</p><p>We do this because the base VM is the actual ‘owner’ of the ‘todos’ which are created by this Todo app, we want to ensure that whenever something must be done on a ‘todo’, the only component of our app which may act on that ‘todo’ is the base VM, and so we see the reason for lines 49–54 of app.js.</p><p>On lines 25–28, the component handles the ‘changetodo’ event, we can guess what it does by examining line 27 in which the value of the ‘todo’ property is set to the value of the ‘todo’ property of the ‘todo’ object received as the data for the ‘changetodo’ event.</p><p>Having examined the ‘app-new-todo’ component, let’s proceed to examine the ‘app-uncompleted-todo’ component.</p><h4>APP-UNCOMPLETED-TODO:</h4><p>As usual, this component is composed of 2 files, index.js and template.html. Let’s begin by examining <strong>‘template.html’</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f0da6c20350b98456ef1ea6306b0352/href">https://medium.com/media/1f0da6c20350b98456ef1ea6306b0352/href</a></iframe><p>On line 3, we note that the ‘p’ element has a ‘<strong>v-show</strong>’ directive which is bound to the ‘<strong>noTodos</strong>’ property of the component. By examining this element we can correctly guess that the intent is to only display the “No todos to display!” message if there happen to be no (uncompleted) todos to show.</p><p>Lines 4–17 are the most interesting portions for us, Vue.js makes it almost trivial to render a list derived from an array or object. We encounter the directives responsible for this behavior on line 5 i.e. <strong>v-for=”todo in todos”</strong>. This directive is ‘saying’ for each ‘todo’ (or whatever name we choose to give it) in the ‘todos’ property of the component, render/create the following HTML elements (lines 6–15).</p><p>Line 6 is an interpolation which inserts the value of the todo property of a ‘todo’ item from the ‘todos’ array into the markup. Lines 8–13 are a group of buttons which allow us to perform actions against the rendered ‘todo’. As we know by now, each directive i.e. ‘@click.stop.prevent’ references a method on the component. Next lets examine the code for the component as contained in <strong>index.js</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56c8eeb9ac61ddf073fe21d66ebafead/href">https://medium.com/media/56c8eeb9ac61ddf073fe21d66ebafead/href</a></iframe><p>As usual, this component has properties such as template, data, props, methods and events. We also encounter for the first time a ‘<strong>life cycle hook</strong>’ called ‘<strong>compiled</strong>’.</p><p>In Vue.js, life cycle hooks allow us to leverage events fired at certain stages of the ‘creation/destruction’ cycle of a Vue VM and to implement specific logic at those points. For our purposes, we will respond to the ‘compiled’ event. Our intent is to trigger certain code just before the VM is inserted into the DOM, at that point in time (i.e. when the ‘compiled’ event is fired) all directives have been linked to the data properties of the underlying VM instance so any changes in state will trigger DOM updates.</p><p>Taking it from the top, we meet the expected assignment of the ‘template’ property with a value referencing the ‘template.html’ file. Next lines 5 &amp; 6 hold the definitions for the ‘todos’ array and the ‘noTodos’ property. From lines 3 &amp; 5 of ‘template.html’ we know that these data properties determine whether or not to display the “No todos to display!” and allow the template to render the ‘list’ of uncompleted ‘todos’ respectively.</p><p>On line 9 we encounter the ‘props’ property and as expected the identifier is in ‘camelCase’; as we may recall, the value of the ‘todosList’ attribute is provided to this component from the base VM i.e. line 32 of ‘index.html’. There are 3 methods which respond to click events on the V (lines 11–22) and they simply trigger custom events which are ‘dispatched’ to the base VM along with the necessary data e.g. the ‘completedtodo’ custom event along with the ‘todo’ object which needs to be marked as complete. Recollect that the use of these custom events allows us to build a loosely coupled application out of the constituent components.</p><p>Lines 24–42 holds the ‘events’ property, as we may recollect, these are custom events fired by the parent VM (in this case the base VM) to which handlers are assigned on this component. The 2 custom events which this component listens for and responds to are the ‘getnewtodo’ and ‘updatetodos’ events.</p><p>When ‘getnewtodo’ is fired, the handler accepts a ‘todo’ object as argument, it confirms that the ‘todo’ is truly an ‘uncompleted’ todo by querying the ‘.completed’ property of the ‘todo’ object (line 26), next it sets the ‘noTodos’ property to ‘false’ (line 28) ensuring that the message is no longer displayed and simply inserts the new ‘todo’ into the beginning index of the ‘todos’ array (line 29).</p><p>When ‘updatetodos’ is fired, the handler first empties its ‘todos’ array (line 34), and then it filters the ‘todosList’ props object for all uncompleted ‘todos’. Recollect that because the ‘’todosList’’ prop is itself bound to the ‘todos’ array of the base VM (lines 32 of index.html and line 15 of app.js) any changes to the ‘todos’ array of the base VM will be automatically reflected in the ‘todosList’ object and this means that all ‘todos’ will be present regardless of their state of completion.</p><p><strong>NB</strong> for the sake of thoroughness allow me to point out that we could have used a ‘<a href="http://vuejs.org/api/#Filters">filter</a>’ so that the ‘todos’ list acting as a ‘prop’ for the ‘app-uncompleted-todo’ component would be those with an uncompleted status alone, however my opinion is that since more than one component requires access to the base VM’s ‘todos’ array for different reasons, its more elegant to make a single prop assignment and handle filtering at the component level.</p><p>Moving forward, after clearing the present ‘todos’ array, the handler filters the ‘todosList’ prop object for only those ‘todos’ which are uncompleted i.e. lines 35 -37, then it assigns the value of the filtered array (line 39) to the ‘todos’ array and then it does something interesting — notice that it returns ‘true’ on line 40.</p><p>In Vue.js, when a custom event is ‘broadcasted’ from a parent VM to the child components, the first component to respond to the event prevents the event from being propagated unless the handler returns ‘true’, this means that in this case because we desire multiple child components to respond to this same ‘updatetodos’ event (as we will see shortly), the handlers on each component <strong>MUST</strong> return ‘true’.</p><p>Lines 43–52 introduce the ‘compiled’ life-cycle hook handler. The intent here is before the component is inserted into the DOM check if there any uncompleted ‘todos’ in the ‘todosList’ object (line 45), if none, then display the no todos message (line 46 and line 3 of template.html), else do not display the message (line 49) and fire the ‘updatetodos’ event on itself (line 50). NB in Vue.js, when we need a VM to fire an event on itself, the syntax to use is “this.$emit(‘eventname’, optionalData);”. With that we complete our examination of the ‘app-uncompleted-todo’ component.</p><h4>APP-COMPLETED-TODO:</h4><p>From the name of the component we can correctly surmise its function — to render all ‘todos’ which the user has completed. As usual, it resides in it’s own directory consisting of two files — index.js and template.html. Let’s begin by examining <strong>template .html</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b3109d541f45af48f1c255f36287b87/href">https://medium.com/media/1b3109d541f45af48f1c255f36287b87/href</a></iframe><p>We notice the no todos message on line 3 and it’s associated ‘v-show’ directive. We also note that the ‘body’ of the HTML is simply a rendering of a list of completed todos specifically lines 5 and 7.</p><p>Moving on to <strong>index.js</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0472ad7de4ed812a9f3917573245450a/href">https://medium.com/media/0472ad7de4ed812a9f3917573245450a/href</a></iframe><p>We notice the expected template and data properties (lines 2–8). We also see that this component also responds to the firing of the ‘updatetodos’ event (lines 11–26) but this time, rather than filtering for <strong>uncompleted</strong> ‘todos’, it filters for <strong>completed</strong> ones (lines 13–17) before returning ‘<strong>true</strong>’ (line 25) so the event can continue propagating.</p><p>The handler for the ‘compiled’ life-cycle event works similarly to that of the ‘app-uncompleted-todo’ component. With that we have concluded examination of this component and we move to the last component, ‘app-all-todos’.</p><h4>APP-ALL-TODOS:</h4><p>This component is very similar to the previously examined one i.e. ‘app-completed-todos’, <strong>template.html</strong> simply renders the ‘list’ of todos contained in the ‘todos’ array of the component VM.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c09b7ca03e568602057fac4edd91bc2a/href">https://medium.com/media/c09b7ca03e568602057fac4edd91bc2a/href</a></iframe><p>Likewise the structure of <strong>index.js</strong> is very similar to that of ‘app-completed-todos’ component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/06a04546144a8d3b2589a27c6202cdd2/href">https://medium.com/media/06a04546144a8d3b2589a27c6202cdd2/href</a></iframe><p>The single <em>significant difference</em> is in the way the ‘<strong>updatetodos</strong>’ event is handled — rather than filtering for <strong>completed or uncompleted todos</strong>, the handler simply <strong>clears</strong> the initial data contained in the ‘todos’ array and then <strong>repopulates</strong> the array with the value of the ‘todosList’ prop object (lines 12–14 of index.js).</p><p>With that, we have walked through the base VM and the component VMs of this simple Todo app built with Vue.js.</p><h4>RECAP.</h4><p>Let’s recap the essential points covered in this article.</p><ol><li>Vue.js allows us to create data driven web applications in a reactive, component based method.</li><li>A Vue.js application follows the MVVM architecture/pattern.</li><li>A basic Vue instance is a VM which has associated V and M components. The V component is defined by an HTML structure to which the VM is bound by referencing the ‘id’ of the HTML element. The M of a VM provides the VM with it’s ‘working data set’ and is simply a javascript object literal or object returned from a function (for components).</li><li>All Vue VM instances are composed of the following properties: el/template, data, computed, methods, events and life-cycle hooks.</li><li>The V of a Vue VM is bound to its VM by directives and data-bindings — this is the relationship which allows the V to be reactive and data driven.</li><li>For best results, any non trivial Vue.js app should be built from a base VM and any number of components.</li><li>Two key constructs which tie a component to it’s parent VM are ‘props’ and ‘events’; these two constructs allow for a component based web app to be loosely coupled.</li><li>There are 3 main approaches to building component based web apps in Vue.js — using custom script tags in the markup/using strings, defining the an component in a single file and splitting the component markup from the code (as we have used in this example).</li></ol><p>In the next article in this series, we will examine how we can build an AJAX capable web app using Vue.js. Thanks for reading and as usual, please reach out if you have questions or comment below.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=32bd03c1a5a9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to manage asynchronous javascript using the Async.js control flow library]]></title>
            <link>https://medium.com/@nohkachi/how-to-use-manage-asynchronous-javascript-using-the-async-js-control-flow-library-f6ffa14e4b70?source=rss-1b66a948a46b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f6ffa14e4b70</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[muyiwa akin-ogundeji]]></dc:creator>
            <pubDate>Fri, 04 Mar 2016 13:19:26 GMT</pubDate>
            <atom:updated>2016-03-08T12:22:08.600Z</atom:updated>
            <content:encoded><![CDATA[<p>From the documentation “Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript”. As javascript developers, we understand that asynchronicity and javascript are almost ‘irrevocably’ intertwined.</p><p>The ‘go-to’ for handling async in javacsript is callbacks! Whether the callbacks are used in a CPS (Continuation Passing Style) as we’re accustomed to, or used with Promises or even as event handlers — the fact remains that when it comes to dealing with async in javascript, callbacks are the key.</p><p>There are many resources which explain callbacks and CPS in great detail so i won’t go there in this post, rather we will examine an aspect of handling sequential or multi-step async in javascript which isn’t as “well understood” as the use of Promises or Events. We will examine how a ‘control flow’ library (specifically Caolan McMahon’s excellent Async.js) can help us manage multi-step/sequential async javascript in a CPS style.</p><h4>THE SEQUENCING PROBLEM:</h4><p>The “problem” we’re trying to solve is how to use the CPS style to manage multi-step async javascript code without deep nesting which leads to the infamous “callback” hell.</p><p>We will examine 3 common use cases where Async.js proves very handy in allowing us to use the CPS option for handling multi-step async javascript.</p><p>I’d also like to point out that while Promises are heavily promoted as the ‘right’ way to handle async in javascript, the fact is that javascript doesn’t enforce a single solution. We will see that one can comfortably use the CPS style by way of a ‘control flow’ library and one can actually implement some really interesting flows without falling prey to ‘callback hell’.</p><h4>CASE 1: Serial Execution.</h4><p>Async.series() is particularly useful when we need to coordinate a series of async operations which must follow one after the other i.e. a chain of events in which the previous event can only start if the succeeding one completes successfully.</p><p>Async.series() has the signature “series(tasks, [callback])” and from the docs “<em>Run the functions in the tasks array in series, each one running once the previous function has completed. If any functions in the series pass an error to its callback, no more functions are run, and callback is immediately called with the value of the error. Otherwise, callback receives an array of results when tasks have completed.</em>”</p><p>An example from the docs:</p><pre>async.series([<br>    function(callback){<br>        // do some stuff ...<br>        callback(null, &#39;one&#39;);<br>    },<br>    function(callback){<br>        // do some more stuff ...<br>        callback(null, &#39;two&#39;);<br>    }<br>],<br>// optional callback<br>function(err, results){<br>    // results is now equal to [&#39;one&#39;, &#39;two&#39;]<br>});</pre><p>If you’re like me, the example wasn’t really helpful in giving me confidence about how to use Async effectively. So let’s consider some code from a <a href="http://54.68.94.131:3030/">recent project</a> i worked on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d6e0895710bc06e17170ba2abd5b2b47/href">https://medium.com/media/d6e0895710bc06e17170ba2abd5b2b47/href</a></iframe><p>The snippet above is for a route handler for a <a href="http://54.68.94.131:3030/">Social network app</a>. The handler is triggered when a new user creates a ‘page’ and hits the endpoint with data from the client.</p><p>For us, the interesting portion of the code begins on line 10. (NB i’ve called the async instance ‘controlFlow’ in the code above). From the Async.js docs, we know that when async.series() is used, we supply an ‘array’ of ‘tasks’ i.e. actions we want to perform in sequence, upon completion of a task, the callback provided to each ‘wrapper’ function is invoked with either an error, or null + data.</p><p>Furthermore, there is an ‘optional’ callback invoked upon completion of the array of tasks which is passed any errors thrown by a task and a ‘results’ array which holds the data values with which each task callback is invoked.</p><p>I know, it may be a handful to wrap our minds around so lets break it down by examining the code above.</p><p>On lines 11 and 27, ‘wrapper’ functions are passed a ‘cb’ argument (i.e. callback), these ‘wrapper’ functions define the individual task we wish to perform in series.</p><p>Lines 11–26 define the first task in which we create a new ‘page’ instance from the ‘PageModel’ constructor which creates a new document for storage in the associated collection. lines 17–20 define a conditional block in which we state that if there’s a database access error caused by the attempt to save the new page to the data store, we do 2 things: 1) log the error (line 18) and 2) invoke the callback and pass the error as the value (line 19).</p><p>If all goes well, then on line 24, we invoke the callback with 2 arguments 1) ‘null’ which means no errors occurred and 2) the saved new page object. Line 24 creates an entry in the ‘results’ array which corrsponds to the new page object that has been persisted to the data store.</p><p>Lines 27–47 define a 2nd task in which we update the user who has created the page with some data which allows the user’s document to ‘know’ the details of the page which the user has just created. Since we need to create a page before we can update the user, we perform these actions in series hence we use async.series().</p><p>Lines 47–53 define the callback which is invoked upon completion of the tasks array. This callback is invoked with 2 arguments 1) an error which only occurs if any one of the tasks in the tasks array invokes it’s own callback with an error e.g line 19. In this case, the entire series fails with the value of the error. 2) if all goes well, a ‘results’ array would have been populated with data that can be retrieved and acted upon.</p><p>Note that a successful series execution results in the route handler responding with a ‘200’ status (line 50) but any error results in a ‘500’ status (line 52).</p><p>The preceding is just an example of how we can use async.series() to coordinate a sequence of async operations that must be executed one after the other. FYI async.waterfall() is a really powerful tool, it differs from async.series() in that the value passed to the callback is made availabvle to the next task in the tasks array i.e. we could have used async.waterfall() to coordinate the code within lines 11–26/47–53 without nesting callbacks.</p><h4>CASE 2: Parallel Execution.</h4><p>Async.parallel() is useful when we need to coordinate a series of async operations which can be executed independently of each other and for which we want to take some action when all the tasks have successfully completed.</p><p>Async.parallel() has the signature “parallel(tasks, [callback])” and from the docs “<em>Run the tasks array of functions in parallel, without waiting until the previous function has completed. If any of the functions pass an error to its callback, the main callback is immediately called with the value of the error. Once the tasks have completed, the results are passed to the final callback as an array</em>”.</p><p>An example from the docs:</p><pre>async.parallel([<br>    function(callback){<br>        setTimeout(function(){<br>            callback(null, &#39;one&#39;);<br>        }, 200);<br>    },<br>    function(callback){<br>        setTimeout(function(){<br>            callback(null, &#39;two&#39;);<br>        }, 100);<br>    }<br>],<br>// optional callback<br>function(err, results){<br>    // the results array will equal [&#39;one&#39;,&#39;two&#39;] even though<br>    // the second function had a shorter timeout.<br>});</pre><p>To clarify the above, lets consider some more code from the same <a href="http://54.68.94.131:3030/">Social network app</a> project i mentioned previously.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9562755420b88ec249216df17e96f3d8/href">https://medium.com/media/9562755420b88ec249216df17e96f3d8/href</a></iframe><p>The snippet above is the route handler which allows a user to retrieve the comments the user’s friend made on a particular post identified by the ‘postID’ variable. The interesting portion for us begins at line 6.</p><p>From the Async.js docs, we know that when async.parallel() is used, we supply an ‘array’ of ‘tasks’ i.e. actions we want to perform in parallel, upon completion of a task, the callback provided to each ‘wrapper’ function is invoked with either an error, or null + data.</p><p>Lines 7 and 24 define the tasks which we want the route handler to execute in parallel, in this case we want to do 2 things … 1) from line 7 we want to retrieve the post which corresponds to the ‘postID’ and 2) from line 24, we want to retrieve the comments which correspond to the ‘commentID’ passed to the ‘GET’ operation as a query string.</p><p>Lines 38–50 define the callback which is called on completion of the tasks in the tasks array. We notice that we can extract the actual post and comment objects from the ‘results’ array (lines 42 and 43), This is why on lines 21 and 36, the task callbacks were invoked with null + data!</p><p>On lines 44–47 the route handler responds to the ‘GET’ by returning the retrieved data, while line 49 would be invoked if either of the parallel tasks had thrown an error.</p><h4>CASE 3: Asynchronous Iteration over a collection.</h4><p>Suppose somewhere in your code you had a collection of data (array or object) and you wanted to perform some async action against each element in parallel. Normally, this would be quite difficult as loops are synchronous by nature and thus would block. Thankfully, Async.each() makes such an action quite straightforward to accomplish.</p><p>Async.each() has the signature “each(arr, iteratee, [callback])” and from the docs “<em>Applies the function iteratee to each item in arr, in parallel. The iteratee is called with an item from the list, and a callback for when it has finished. If the iteratee passes an error to its callback, the main callback (for the each function) is immediately called with the error.</em></p><p><em>Note, that since this function applies iteratee to each item in parallel, there is no guarantee that the iteratee functions will complete in order</em>”.</p><p>An example from the docs:</p><pre>// assuming openFiles is an array of file names<br><br>async.each(openFiles, function(file, callback) {<br><br>  // Perform operation on file here.<br>  console.log(&#39;Processing file &#39; + file);<br><br>  if( file.length &gt; 32 ) {<br>    console.log(&#39;This file name is too long&#39;);<br>    callback(&#39;File name too long&#39;);<br>  } else {<br>    // Do work to process file here<br>    console.log(&#39;File processed&#39;);<br>    callback();<br>  }<br>}, function(err){<br>    // if any of the file processing produced an error, err would equal that error<br>    if( err ) {<br>      // One of the iterations produced an error.<br>      // All processing will now stop.<br>      console.log(&#39;A file failed to process&#39;);<br>    } else {<br>      console.log(&#39;All files have been processed successfully&#39;);<br>    }<br>});</pre><p>To clarify the above, we’ll once again consider some more code from the <a href="http://54.68.94.131:3030/">Social network app</a> project.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19ec9a00c5fb658bf700f69dfd951a8a/href">https://medium.com/media/19ec9a00c5fb658bf700f69dfd951a8a/href</a></iframe><p>The snippet above is the route handler which allows a user to retrieve a list of the user’s friends. The interesting portion for us begins at line 5.</p><p>From the Async.js docs, we know that when async.each() is used, we supply an array of values against which the ‘iteratee’ function is applied. The iteratee takes 2 args 1) a value from the array and 2) a callback to be called once the action taken against the value has been completed.</p><p>NB In this case, if there’s no error the ‘task’ callback is either called with ‘null’ or no args are passed e.g. line 18. This means that any action to be taken upon data created during the iteration can only act on some data external to the async.each() logic block… we see this on lines 4 (declaring a ‘friendList’ array outside the async.each() logic block), 12–17 (adding an entry to the ‘friendsList’ array) and 26–28 (returning the friendsList array upon successful iteration over the list i.e. req.user.friends).</p><p>The array to be passed to async.each() is derived from the ‘friends’ array of the user i.e. req.user.friends (recall that passport appends a ‘user’ object to the ‘req’ which is a reference to the user object stored in the database). In the database, the ‘friends’ array is a collection of email addresses. Thus on line 5, the value passed to the iteratee function is an email address.</p><p>As usual, any errors require we invoke the ‘task’ callback with an error argument e.g. line 10 and if there’re no errors we simply invoke the callback without args e.g. line 18.</p><p>Upon successful iteration over the list we respond with data e.g. lines 26–28 or in the case of an error we return an error page.</p><p>These 3 cases are straightforward examples of how control flow libraries e.g. Async.js can be very helpful in allowing us to deal with async javascript using a CPS style. Let’s now examine a use case in which we combine different flows to achieve some interesting results.</p><h4>Combining flows.</h4><p>Let’s consider the following code snippet from the <a href="http://54.68.94.131:3030/">Social network app</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb48a6d5e04f968f9d11cb734b37886e/href">https://medium.com/media/fb48a6d5e04f968f9d11cb734b37886e/href</a></iframe><p>The preceding code is a socket handler which provides real time notification to the connected user’s friends when the user creates a new post. To achieve this feature, we nest an async.each() block, within an async.parallel() block by making the async.each() block a component one of the ‘task wrappers’ in the ‘tasks’ array of the async.parallel() block.</p><p>Line 5 begins the async.parallel() block, lines 6 and 32 define the constituent tasks of the async.parallel() block’s ‘tasks’ array. The goal of this code is to do 2 things 1) update the user’s data in real time when a new post is created and 2) ‘simultaneously’ send a real time message to the user’s friends that the user has created a new post.</p><p>There’s nothing new in the overall composition of the async.parallel() block, it has 2 tasks in it’s tasks array and when the tasks complete, the callback (line 71) is invoked and the necessary action is taken depending on whether errors occur within the tasks or not.</p><p>What’s different is how the 2nd task (lines 32–70) is composed. We start by running a query to extract the connected user from the database (line 33), [please see a <a href="https://medium.com/@nohkachi/the-importance-of-documentation-or-how-i-discovered-how-to-share-express-sessions-with-socket-io-d8d2b6bd42e5#.o6ipwnol7">previous post</a> which explains the significance of ‘ID’], if the user has friends, then we supply the user’s friends array to async.each() (line 43) and then perform a series of actions for each friend (specifically confirming the friend is online and then notifying the friend of the user’s action i.e. new post).</p><h4>Conclusion.</h4><p>Async.js is a really powerful tool which allows us to more effectively and flexible handle async in javascript. Remember that javascript is such a powerful and flexible language that we as developers are able to express ourselves in a variety of ways without being constrained by a single ‘right way’.</p><p>Thanks for reading, as usual please leave comments or contact me if you have any questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f6ffa14e4b70" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Importance of Documentation or “How i discovered how to share Express sessions with Socket.io”.]]></title>
            <link>https://medium.com/@nohkachi/the-importance-of-documentation-or-how-i-discovered-how-to-share-express-sessions-with-socket-io-d8d2b6bd42e5?source=rss-1b66a948a46b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d8d2b6bd42e5</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[sessions]]></category>
            <dc:creator><![CDATA[muyiwa akin-ogundeji]]></dc:creator>
            <pubDate>Thu, 03 Mar 2016 17:00:15 GMT</pubDate>
            <atom:updated>2016-03-03T17:01:06.036Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi guys, it’s been a little while since my <a href="https://medium.com/@nohkachi/the-key-to-javascript-23aba61b7aee#.1asyj9fst">last post</a>, i’ve been working on a small project — building a generic <a href="http://54.68.94.131:3030/">social network app</a> with the VMENS (Vue.js, MongoDB, Express, Node, Socket.io) stack. This post begins a series of posts in which i share my experiences building the app and how i resolved several issues i encountered. As usual, <a href="https://github.com/oakinogundeji/express-socket.io_sessions">the code</a> for this app is available on <a href="https://github.com/oakinogundeji/express-socket.io_sessions">github</a>.</p><h4>Background:</h4><p>Socket.io is a really great library for adding real time functionality to our applications. As Javascript Web developers, socket.io is one of the major tools we use in addition to the NEM (Node, Express and MongoDB) stack for building DIRTy (Data Intensive Real Time) web applications.</p><p>However, a serious issue occurs when we have an idea for a feature or functionality and we’re studying the documentation but to our frustration — we don’t find detailed info with respect to the issue we’re trying to resolve.</p><p>I found myself in this situation quite recently while building a project, i wanted a way to share an Express session with Socket.io without needing to include the <a href="https://www.npmjs.com/package/express-socket.io-session">express-socket.io-session</a> library or change my code architecture style by conforming to <a href="https://github.com/techpines/express.io">express.io</a> styles or using <a href="http://mono.software/2014/08/25/Sharing-sessions-between-SocketIO-and-Express-using-Redis/">redis</a> etc, what i wanted and felt was possible from my initial research was a ‘native’ way to share an Express session with socket.io in order to allow any route handler access to the underlying socket instance of the connected client, and also to provide the socket instance of the connected client access to the serialized user from the session store (and access to all that user’s data as necessary).</p><p>I didn’t want to use the work around of storing socket ‘nicknames’ in an object and then accessing those sockets by nicknames — this would merely provide the route handlers with access to the underlying socket but not give the socket access to the serialized user.</p><p>After much searching, i <a href="http://stackoverflow.com/questions/25532692/how-to-share-sessions-with-socket-io-1-x-and-express-4-x">found a path</a> that led to the <a href="http://stackoverflow.com/questions/25532692/how-to-share-sessions-with-socket-io-1-x-and-express-4-x">solution</a> i eventually adopted.</p><blockquote>The solution is surprisingly simple. It’s just not very well documented. It is possible to use the express session middleware as a Socket.IO middleware too with a small adapter like this:</blockquote><h4>The Problem:</h4><p>From the quote above, we can see what “the problem” is — a solution to an issue which wasn’t well documented. Furthermore (at least for me..) i wasn’t quite clear on how exactly i would access the underlying serialized user (from the socket.io module) or socket (from my route handlers). So i had to do some digging and tinkering before developing a solution which i’m very pleased with.</p><p>Join me as we walk through the process of understanding together.</p><h4>Elements of a solution:</h4><p>From the <a href="http://stackoverflow.com/questions/25532692/how-to-share-sessions-with-socket-io-1-x-and-express-4-x">resource</a> which i shared earlier on, we notice that the ‘key’ to achieving our goal is to share the session middleware we use within our Express app with the socket.io instance. Specifically this consists of 2 steps (taken directly from the post, but we will soon use our own versions):</p><ol><li>Within ‘app.js’ i.e. the main module for the app (i.e. as used in the post) we do the following:</li></ol><pre>var sessionMiddleware = session({<br> store: new RedisStore({}), // XXX redis server config<br> secret: “keyboard cat”,<br>});</pre><pre>app.use(sessionMiddleware);</pre><p>2. And also in that same module, presuming that we’ve ‘required’ the socket.io package we do:</p><pre>sio.use(function(socket, next) {<br>    sessionMiddleware(socket.request, socket.request.res, next);<br>});</pre><p>The preceding steps then make it possible for the following:</p><pre>sio.sockets.on(&quot;connection&quot;, function(socket) {<br>  socket.request.session // Now it&#39;s available from Socket.IO sockets too! Win!<br>});</pre><p>The preceding 2 steps are the elements for the solution we will build, however, as is, there’re some questions that need to be answered.</p><ol><li>What exactly does “socket.request.session” expose?</li><li>How is the exposed object from (1) above related to the ‘req.session’ object? NB we are assuming that the session middleware module we are using is ‘express-session’.</li></ol><p>Lets’s answer these 2 questions in order to gain a deeper understanding of what the submitted solution makes possible and we will then be able to understand just what we need to do in order to modify the solution for our own needs.</p><h4>What’s exposed by “socket.request.session”:</h4><p>To answer this question, we’ll build a small app, furthermore, rather than placing everything within one file we will split the app into modules just as we would for a ‘non trivial’ app.</p><p>The app will have the following views:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/531/1*Wc6IT38WaC4xl5rj6k4KLA.png" /><figcaption>login.html</figcaption></figure><p>The login screen which serves as the homepage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*uvHiwGLGDn2Ze5Cnvhjb9Q.png" /><figcaption>signup.html</figcaption></figure><p>The signup page for new users to sign up for access to the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/1*KHXv62th9U706vyVwhoXxw.png" /><figcaption>dashboard.html</figcaption></figure><p>Upon successful signup, a dashboard is rendered. Notice a couple of things:</p><ol><li>In the exposed console, you see that some data is received from the socket connection, specifically a firstName and lastName.</li><li>On the dashboard, this data is displayed as the user’s full name.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*LyU8kOG8-Si1GLcvmEWFXg.png" /><figcaption>dashboard_disconnected</figcaption></figure><p>When the client is disconnected from the server, we notice that the user’s full name is no longer displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*FnrWv5Z_PqZFpatBp1-BbA.png" /><figcaption>dashboard_reconnected</figcaption></figure><p>Upon successful reconnection, the data is received from the socket and the full name is displayed once again.</p><p>For your convenience you can <a href="https://gist.github.com/bfd8e708345aa6248746.git">download</a> or copy the following project scaffold script:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d4987b5d3461c2af4d59ac1a92c90cb/href">https://medium.com/media/3d4987b5d3461c2af4d59ac1a92c90cb/href</a></iframe><p>This will help us quickly scaffold an application. I’m going to jump ahead a little here but i promise we’ll tie everything together neatly. We will need to implement local authentication using passport, and this means we’ll also need to build at least one ‘user’ model via mongoose. So we first run ‘npm init’ to create a ‘package.json’ file then <a href="https://gist.github.com/3fb844a0ad3d0c53590d.git">download</a> or copy the following script to run ‘npm install’ with the modules we will use.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b67627dfb4a9c98464d1f5524fd1bf2/href">https://medium.com/media/5b67627dfb4a9c98464d1f5524fd1bf2/href</a></iframe><p>Having installed our modules we quickly build out the following app modules — app.js, socket.js, users.js, routes.js, config.js, development.js, passport.js, and isLoggedIn.js. We also build 3 views login.html, signup.html, dashboard.html.</p><p>The 3 modules we are interested in are ‘app.js’, ‘routes.js’ and ‘socket.js’.</p><p><strong>app.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4fd257a0942b96cb0f6f3e1310b748e3/href">https://medium.com/media/4fd257a0942b96cb0f6f3e1310b748e3/href</a></iframe><p>For us, the interesting portions of this file are from lines 90–100, we see how the session middleware is abstracted into a reusable variable (lines 90 — 92), then we are able to 1) use it in the Express app as usual (line 97) and 2) just as suggested by the <a href="http://stackoverflow.com/questions/25532692/how-to-share-sessions-with-socket-io-1-x-and-express-4-x">resource</a> where we discovered the elements we need we are able to use it as middleware for socket.io (lines 98 — 100).</p><p>NB We had previously ‘required’ socket.io on line 14.</p><p>The work done on these lines lay the foundation for what follows.</p><p><strong>socket.js</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b4a42c629d2c6af395ee345f3fca441/href">https://medium.com/media/4b4a42c629d2c6af395ee345f3fca441/href</a></iframe><p>The interesting portions for us are lines 22–28 and 54.</p><p>On line 22, we finally answer the question — what is exposed by “socket.request.session”. If we examine our terminal we should see something similar to the following…</p><pre>the socket session object Session {<br> cookie: <br> { path: ‘/’,<br> _expires: Fri Mar 04 2016 16:33:41 GMT+0100 (WAT),<br> originalMaxAge: 86400000,<br> httpOnly: true },<br> passport: { user: ‘56d859553443f3d409df1de2’ },<br> lastModified: Thu Mar 03 2016 16:33:41 GMT+0100 (WAT) }</pre><p>NB (the assumption is that a user has logged on to the app).</p><p>Notice the ‘passport’ property? Line 23 allows us to see just what this data is, in the terminal you should have something like…</p><pre>the actual serialized user from passport 56d859553443f3d409df1de2</pre><p>If you check your MongoDB database, you’ll be pleasantly surprised to see that this value is the value for the serialized user of the session.</p><p>On line 28, we map the underlying socket instance to the serialized user. This allows us to access the underlying socket from anywhere in our app by simply passing a reference to the user’s “_id” to the ‘userSockets” object exposed by line 54.</p><p>Lines 29–39 are responsible for using the “_id” of the serialized user to access the database and retrieve additional data about the user which isn’t exposed by the actual endpoint (we’ll see this in routes.js).</p><p>Having answered question 1, we can answer question 2.</p><h4>How is the exposed object from “socket.request.session” related to the ‘req.session’ object?</h4><p>To answer this question we need to examine ‘routes.js’.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56ae0e1b6de00c0ac35c98b371d9df54/href">https://medium.com/media/56ae0e1b6de00c0ac35c98b371d9df54/href</a></iframe><p>For our purposes, the interesting portions are lines 84–95.</p><p>On line 92, we examine the actual ‘req.session’ object which the ‘express-session’ middleware extends the base ‘req’ object with when session support is enabled for an Express app.</p><p>In the terminal we should have something like this…</p><pre>the request session object Session {<br> cookie: <br> { path: ‘/’,<br> _expires: Fri Mar 04 2016 16:33:41 GMT+0100 (WAT),<br> originalMaxAge: 86400000,<br> httpOnly: true },<br> passport: { user: ‘56d859553443f3d409df1de2’ },<br> lastModified: Thu Mar 03 2016 16:33:41 GMT+0100 (WAT) }</pre><p>If we compare this object with that exposed by “socket.request.session” we’ll notice they’re the exact same object! How cooool is that? And because of our access to the ‘userSockets’ object, we can do some interesting stuff (i’ll show an example real soon).</p><h4>The full solution:</h4><p>While the initial pointer from the <a href="http://stackoverflow.com/questions/25532692/how-to-share-sessions-with-socket-io-1-x-and-express-4-x">resource</a> was helpful, we find that we gain extra cool benefits by actually working with the ‘_id’ of the serialized user i.e. what we really need access to is “socket.request.session.passport.user” rather than simply “socket.request.session”. The reason as we know by now is that the former allows us to give the socket server access to the underlying user object from the datastore and this allows us to do very cool real time stuff useful for applications like social media apps (details in a future post).</p><p>By the way, you may want to examine <a href="https://gist.github.com/9c27264ac7a7cd81c7a5.git">‘dashboard.html’</a> which shows how we insert and remove the additional data received from the socket into the DOM.</p><h4>Conclusion:</h4><p>As promised, let’s briefly review how we can use our new understanding to do some cool stuff. Below is a snippet of the socket.io code used in the <a href="http://54.68.94.131:3030/">social network app</a> i just finished working on.</p><p>When a user makes a comment, socket.io is able to notify only the user’s friends by accessing the “_id” of the serialized user (i.e. the ‘ID’) variable as seen on line 3.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5b8dc20ce0708952184c65aaed6b2f4d/href">https://medium.com/media/5b8dc20ce0708952184c65aaed6b2f4d/href</a></iframe><p>For us, the key to this feature is line 3! By having access to the “_id” value for the user making a comment (as we have come to understand, this is possible by sharing the Express session with socket.io), we can use async.each() (called ‘controlFlow’ in this example) to iterate over each friend in the user’s “friend’s” array and then by accessing their own “_id”, we can emit the user’s action to just that person — how cool is that?</p><p>Thanks for reading, as usual please leave comments below or contact me for any clarification.</p><p>NB I’ll be starting a YouTube channel soon… keep following!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d8d2b6bd42e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[THE KEY TO JAVASCRIPT]]></title>
            <link>https://medium.com/@nohkachi/the-key-to-javascript-23aba61b7aee?source=rss-1b66a948a46b------2</link>
            <guid isPermaLink="false">https://medium.com/p/23aba61b7aee</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[muyiwa akin-ogundeji]]></dc:creator>
            <pubDate>Thu, 21 Jan 2016 13:58:48 GMT</pubDate>
            <atom:updated>2016-01-21T13:58:48.590Z</atom:updated>
            <content:encoded><![CDATA[<p>Javascript (JS)is an amazing language, it’s history is full of drama from creation through being scorned as a ‘toy language’ and now becoming a mainstream language ‘recognized’ as suitable for creating performant, scalable web applications.</p><p>Despite the increasing popularity of JS it still is a ‘misunderstood’ language (as Douglas Crockford said). A major reason for being misunderstood and improperly applied is that many users of JS lack the key which unlocks the full potential of this amazing and dare i say — revolutionary — programming language.</p><p>You see, many people who use JS ‘speak’ JS with an ‘accent’ (i got that from Eric Elliot), this means that either because of their background in other programming languages (C, C++, Java etc) or because of how they learnt JS, they approach JS with a ‘bias’ which clouds how they perceive and apply JS in their projects. A really good example of this ‘accent’ is trying to implement ‘inheritance’ using ‘classes’ (read ‘constructor function calls’) rather than implementing inheritance though ‘objects’ (read ‘the prototype chain’).</p><p>In this article we will come to understand the ‘key’ to JS and discover how this ‘key’ unlocks for us the full power of this amazingly powerful and expressive programming language, we will come to understand that JS confers us i.e. developers with the power to express our ideas as we see fit without the constraints of many traditional programming languages, we will also come to understand that JS is not flawed in any way but is simply what it is — a language developed to address a problem but which is flexible enough to be applied to other problem domains.</p><p>Of course this doesn’t mean JS is perfect — no humanly devised solution is, but JS is just right for what it needs to be used for and we will come to appreciate this through the course of this article. This is why statements such as “Atwood’s Law” have been coined.</p><h4>THE KEY IS NOT A SINGLE THING</h4><p>The first thing we need to understand is that the ‘key’ to JS is not a single ‘thing’ — rather it’s an ‘alloy’, an ‘amalgam’ a ‘gestalt’ (if you prefer) composed of parts which beautifully combine to form a whole which is greater than the sum of the parts.</p><p>The ‘key’ to JS is composed of 1) Objects 2) Functions and 3) Asynchronity. These 3 elements combine to unlock the full power of JS. Let’s begin to understand the ‘key’.</p><h4>OBJECTS</h4><p>A JS Object is a collection of ‘properties’, each property is a ‘mapping’ between a ‘key’ and a ‘value’. A ‘value’ can be any valid JS ‘value type’ — this is why what we call ‘methods’ in JS are more accurately called ‘properties’ since they’re simply properties whose value is a function!</p><p>Ok, so we get that JS Objects are collections of ‘properties’ is that all? No! Because they’re ‘first class types’ JS Objects can be passed around any JS code, thus JS Objects are a very clean way to encapsulate ‘state’. This makes them very important in developing maintainable code. Since the JS Object is a value, it means we can mutate the ‘state’ we’re interested in by simply modifying the appropriate ‘property’ of the object that represents that ‘state’. This means that a function can have all the ‘state’ it needs to effect some change represented in totality by the appropriate object. This is a key insight into understanding how JS Objects can be used to represent interfaces between the user and the application (i.e. UIs) and also between different applications (i.e. APIs).</p><p>Furthermore, unlike the vast majority of ‘Object Oriented’ programming languages, JS makes it really easy and straightforward to work with ‘Objects’ as representations of either ‘real world’ entities/constructs or ‘abstract’ entities/constructs. In JS, an Object can be created and manipulated without needing a ‘blueprint’ i.e. ‘class’ to define it’s behavior!</p><p>Do we need to work with a ‘car’ object? Simply create one as follows:</p><pre>var car = {<br>make: &#39;Ford&#39;,<br>type: &#39;salon&#39;,<br>engine_capacity: &#39;V8&#39;,<br>start: function () {<br>return console.log(&#39;Engine started!&#39;);<br>},<br>accelerate: function () {<br>return console.log(&#39;Going faster!&#39;);<br>},<br>brake: function () {<br>return console.log(&#39;Slowing down!&#39;);<br>}<br>};</pre><p>Just like that we’ve created a ‘car’ object. And if we need more cars — we simply create them. This makes JS very useful as it removes a layer of abstraction i.e. the ‘class’ and allows us to reason more starightforwardly about our code.</p><p>So why is the use of ‘class’ so popular? I suggest 2 reasons.</p><ol><li>‘Typecasting’: In traditional OO languages, an object can’t simply ‘be’ an object — it has to be an ‘instance’ of a ‘class’, so you’d have ‘people’ objects and ‘car’ objects and so forth. Because the ‘class’ created the object you could identify what an ‘object’ is by checking it’s type. Something like:</li></ol><pre>//this is imaginary<br>var car = instance of Car class;<br>typeof car;//Car<br></pre><p>But in JS, objects can simply ‘be’ objects and so we would have the following:</p><pre>var car = {<br>make: &#39;Ford&#39;,<br>------------<br>};<br>typeof car; &#39;object&#39;</pre><p>For many people from the traditional OO world, this is very unpleasant! A ‘car’ should be a ‘Car’ object and not simply an ‘object’! But this isn’t so in JS — in JS we don’t have ‘types’ of objects, we simply have objects. This is a key insight to allow us to use JS effectively.</p><p>I could go on and on but allow me to refer you to a <a href="http://shop.oreilly.com/product/0636920033738.do">most valuable resource</a> by Kyle Simpson. This book will provide key insight into the true nature of objects in JS.</p><p>2. ‘Inheritance, Polymorphism, Encapsulation’: These are treasured patterns in the world of OO and they are valid solutions to the problems they were created to address, however in JS, things don’t work the same way as it does in traditional OO. In traditional OO, in order to create multiple ‘car’ objects, we create multiple ‘instances’ of the ‘Car’ class. This is done so that the default ‘behavior’ of the ‘car’ object conforms to a pattern defined on the ‘Car’ class but is still modifiable on any ‘car’ object if we so choose (this is essentially what ‘inheritance’ is all about — a mechanism which allows objects to access functionality (properties/methods) not defined on themselves). In JS because we can directly create and manipulate Objects, a different mechanism for implementing inheritance was adopted and that is the ‘infamous’ prototypical inheritance.</p><p>What this means in essence is that every object in JS is linked to some other object (even ‘null’) called it’s ‘prototype’and it ‘inherits’ some default behavior from that object. For instance:</p><pre>var obj = {};<br>obj.toString();//&quot;[object Object]&quot;</pre><p>Hold up! How come ‘obj’ didn’t throw an error when an undefined method ‘toString()’ was called on it? This is the power of prototypical inheritance!</p><p>What if we want to create multiple ‘car’ objects or even multiple ‘Ford’ cars which differ only in some details — maybe color, engine type etc? Surely the ‘only way’ that is possible is by defining a ‘class’ and the creating instances right? In traditional OO, that would be so, but in JS we chuckle with glee! Behold:</p><pre>var fordProtoype = {<br>start: function () {<br>return console.log(&#39;Engine started!&#39;);<br>},<br>accelerate: function () {<br>return console.log(&#39;Going faster!&#39;);<br>},<br>brake: function () {<br>return console.log(&#39;Slowing down!&#39;);<br>}<br>};</pre><pre>function fordFactory(configObj) {<br>var newFord = Object.create(fordPrototype);<br>newFord.color = configObj.color;<br>newFord.model_name = configObj.model_name;<br>newFord.topSpeed = configObj.topSpeed;<br>return newFord;<br>}</pre><pre>var fordEscort = fordFactory({<br>color: &#39;black&#39;,<br>model_name: &#39;Escort&#39;,<br>topSpeed: &#39;240 km/h&#39;<br>});</pre><pre>fordEscort.start();//&#39;Engine started!&#39;</pre><p>The preceding code snippet shows how ‘easy’ it is to implement ‘inheritance’ in JS without needing to ‘accent’ our JS with overtones from traditional OO which merely ‘deceive’ us into thinking we know what we’re doing and what’s going on when the reality is that JS is doing something totally different under the hood. Likewise other concepts such as ‘encapsulation of private data etc’ and ‘polymorphism’ are implementable in JS using the proper JS constructs without needing to ‘coerce’ JS into appearing to behave in a way which it is totally alien to it’s nature.</p><p>Having said that, is it possible to implement ‘classes’ in JS to achieve some functionality or the other? Yes it is, by using functions and making ‘constructor’ calls i.e. calling the function with the ‘new’ keyword, we can implement classes (or simply using ES6 ‘class’ keyword) but it’s important to understand what’s happening under the hood and realize that we’re not truly creating blueprints for object instances but merely creating prototypical linkages between one object type (i.e. the ‘instance’) and another (i.e. the ‘class’ because in JS, Functions are objects!).</p><p>Again i refer you the <a href="http://shop.oreilly.com/product/0636920033738.do">excellent book by Kyle Simpson</a>, he does a far better job than i in making the nature of JS objects very clear.</p><p>The fact is that the flexible nature of JS combined with the power of JS Objects allows us to really screw ourselves up when we don’t have a clear understanding about the nature of objects in JS. Objects are an important element which makes up the ‘key’ to JS and a clear understanding of what they are and how they function is essential if we are to truly master JS.</p><h4>FUNCTIONS</h4><p>Functions! Some believe that functions are the ‘key’ to JS, this is because in JS Functions are so central to implementing any non-trivial operation that it’s unimaginable to think something else could be just as important.</p><p>As we’ve seen already, Objects are also really important in unleashing the full power of JS. One is not more important than the other, they play complementary roles in making JS such a powerful language.</p><p>The first thing to understand about JS functions is that in JS, functions are actually a special variant of the ‘Object’ type! This is a reason why JS functions are ‘first class citizens’ and can be passed around JS code just like any other JS ‘value type’.</p><p>First class functions makes it possible to implement a functional programming style in JS when necessary — that ability is so important as it allows JS to be used in a powerfully expressive yet declarative manner when necessary. For instance, compare the following code snippet:</p><pre>//procedural imperative implementation 1<br>var arr = [1,2,3,4,5,6,7,8,9], i, len = arr.length;<br>for (i = 0; i &lt; len; i++) {<br>  console.log(arr[i]);<br>}</pre><pre>//declarative implementation 2<br>var arr = [1,2,3,4,5,6,7,8,9];<br>arr.forEach(function (el){<br>  console.log(el);<br>});</pre><p>The difference in the 2 code samples is clear, the first is what obtains in traditional OO languages and the 2nd is what obtains in traditional Functional Programming languages — both are possible with JS!</p><p>Functions in JS are used to do 2 things 1) provide a ‘relationship’ between input ‘data’ and output ‘result’ — this is particularly so when we do not want ‘side effects’ in our code or we require that the logic represented by the function simply ‘compute’ the result of some operation on a given piece of data. 2) mutate ‘state’ by ‘doing’ something e.g. if we wanted the function to respond to user input and perform some action which provides feedback to the user by changing the application in some way.</p><p>There are different ways through which JS functions can be ‘ created’ e.g. function declaration or function expression, JS functions can also be anonymous or named. Because JS functions are values, they can be passed to other functions as arguments this is why JS is such a natural fit for ‘event driven’ programming!</p><p>JS functions are the key to creating web applications which are responsive to user actions, they’re the ‘secret’ to building non-blocking, asynchronous applications and they make it ‘easy’ to implement some patterns in JS which are more difficult in other OO languages.</p><p>Because JS functions are objects, they require a reference to the ‘context’ within which they are executed. This reference is provided by the ‘this’ variable which points to the ‘calling/owning’ context of the JS function within which the ‘state’ of the JS function has meaning.</p><p>In other words, ‘this’ is what allows the variables which a JS function uses to perform it’s operation to have ‘meaning’ i.e. to have a direct reference in the memory space allocated to the JS function. <a href="http://shop.oreilly.com/product/0636920033738.do">Kyle’s book</a> explains ‘this’ in greater detail and a <a href="https://medium.com/@nohkachi/what-s-wrong-with-javascript-pt2-ce06fbd4da67#.zg94jbws7">previous article</a> which i wrote also provides background on ‘this’.</p><p>Because of the preceding concept and the fact that JS functions are also values — the ‘closure’ mechanism can be used to retain the ‘state’ of a JS function in a similar manner to how a JS object can be used to encapsulate ‘state’. This is why <a href="http://people.csail.mit.edu/gregs/ll1-discuss-archive-html/msg03277.html">Anton came to understand</a> that closures and objects achieve the same goal — they encapsulate state!</p><p>These insights into JS functions provide the merest introduction to the reason they are such an important component of the ‘key’ to JS. It’s impossible to master JS without mastering JS functions, it’s impossible to use the full power of JS if the full power of JS functions is neglected.</p><h4>ASYNCHRONITY</h4><p>In the world of ‘event driven’ programming — JS is king! The reason is because JS functions, objects and the single threaded nature of JS (plus other ‘stuff’ like the event loop, run to completion etc) make it much easier in JS to implement async programs than in almost any other programming language.</p><p>When a user hovers over an element with a mouse, JS’s async capabilities are what allow it to execute the proper function in response to this ‘event’ and provide the appropriate response by the application.</p><p>There are 3 ‘mechanisms’ in JS which make it possible to effectively handle async: 1) Single Threaded nature 2) Run to Completion 3) Events and the Event loop.</p><p><strong>Single Threaded Nature:</strong> JS is single threaded by nature, this means that there’s only one JS thread per browser window/tab. When this is coupled with JS ‘interpretation’ of code i.e.e line by line execution, it means that any code block currently running will have each statement executed line by line. By itself, this doesn’t tell us much but when combined with the next point things begin to become clearer.</p><p><strong>Run to Completion:</strong> This attribute of JS ensures that any piece of code currently under execution cannot in anyway be interrupted before it returns. When combined with the Single threaded nature of JS it implies that if a callback is invoked asynchronously from within a currently executing statement, that callback cannot later interrupt the executing code if it returns before the code that called it completes.</p><p>Take a moment to review what i just said — it’s really powerful stuff! It gets better and becomes clearer when we examine the 3rd piece of the ‘puzzle’ — Events and the Event Loop.</p><p><strong>Events and the Event Loop:</strong> What makes a function async? It’s not what you think i.e. merely accepting a callback as an argument doesn’t make a function async, consider the following:</p><pre>function foo(val, cb) {<br> debugger;<br> cb(val);<br>}</pre><pre>function bar(val) {<br> return val * val;<br>}</pre><pre>foo(10, bar);//100</pre><p>In the preceding code snippet, it may appear that ‘foo’ is asynchronously calling ‘bar’ i.e. ‘foo’ returns before ‘bar’ is called, but if you examine the call stack, you’ll see that what actually happens is that ‘bar’ is synchronously called from within ‘foo’ and ‘bar’ returns before ‘foo’!</p><p>Consider another code snippet:</p><pre>function foo(val, cb) {<br>  return setTimeout(function () {<br>    return cb(val);<br>  }, 1000);<br>}</pre><pre>function bar(val) {<br>  return console.log(val * val);<br>}</pre><pre>foo(10, bar);//returns timer id<br>//at least one second later<br>100</pre><p>To clearly understand the difference between the 2 code snippets you need to examine the debugger — you’ll notice that for the 2nd snippet — ‘foo’ actually returns and then at least 1 second later ‘bar’ returns!</p><p>So what’s going on? It’s the power of the 3rd piece of the JS asynchronity puzzle — events and the event loop.</p><p>In JS, a function can only be called async when it’s invoked in response to some event which takes place at some undetermined time in the future. Lets step back for a minute- we know that JS is single threaded and has a run to completion operation and we understand what that means, now we need to understand the place of events and the event loop.</p><p>In JS runtime environments, ‘events’ happen all the time. Almost every single action that takes place in the JS environment fires an event, these events can be ‘listened for’ by our code and we can cause JS to invoke the appropriate piece of code when the event occurs. When events are fired they are placed in a queue, this queue is visited by the JS runtime host e.g. a browser whenever the currently executing JS thread ends.</p><p>SO what happens is we invoke some code, it runs to completion, perhaps during the time it was running some actions took place on the UI, data was received over the network etc these other I/O operations will be ‘noted’ because when they occur they fire events which are placed on the queue — but while the currently running code is executing, these events will not be responded to (which is why its a bad idea to make long running code execute synchronously — it causes the browser to ‘freeze’) until the presently executing code (current thread) has completed and JS has returned control to the host environment.</p><p>When the host gets control from JS, it examines the queue and informs JS of the next event that’s available — if some code has been assigned to handle this event, then JS invokes the function and causes it to run to completion before returning control to the host. It’s this continuous placing of events on the queue and checking the queue by the host (after control has been returned by JS) that is called the event loop.</p><p>Implicitly or explicitly, a function has to be assigned to an event in order to be invoked when the event occurs. Consider the foo function which used the timer, by design, implicitly and internally, JS assigns the callback passed to the timer to be invoked after the provided duration (1000 ms) has elapsed. This is why after the elapsed time JS ‘knows’ the proper function to call.</p><p>These 3 mechanisms make JS absolutely great for developing event driven applications which implement a non blocking I/O structure. An in our modern world of big data — which application can afford to neglect this capability? None! That’s why almost all the giants of big data — Facebook, Google, Twitter, Paypal etc have developed JS frameworks or libraries to take advantage of the power of JS in handling async!</p><p>These 3 elements — JS Objects, Functions and Asynchronity are truly the ‘key’ to unlocking the full power of JS and setting us firmly on the road to mastery.</p><p>I’d have liked to really dig deep into these 3 subjects but i’m sure you can get better background on them from more qualified sources than me.</p><p>Thank you for reading, please leave comments below or reach out to me on twitter.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23aba61b7aee" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>