Share Tweet Reccomend

Native JavaScript Promises

Promises are awesome and the new native promise JavaScript implementation is great and pretty much entirely supported across all modern browsers. In the past developers used various different libraries like jQuery.Deferred() or Q to handle their promise implementations. However, with the native Promise object now in JavaScript in most if not all environments, these are no longer really needed. They’ll still work fine, but it would be advisable to start moving towards the native implementations of promises.

Below are 2 different examples of how you could use the native Promise object in JavaScript…

//2 different examples of promise usage.  
jQuery(document).ready(function() {  
    
    var test = [];

    function getPost(id){
        var def = new Promise(function(resolve, reject){
            jQuery.ajax({ 
                url: "https://jsonplaceholder.typicode.com/posts/" + id,
                type: "GET",
                dataType: "json",
                success: function(data){
                    test.push(data);
                    resolve(data)
                },
                error: function(){
                    reject();
                }
            }); 

        });

        return def;
    }

    // Implementation #1
    getPost(1).then(function(data){
        console.log(data);
        return getPost(2); 

    }).then(function(data){
        console.log(data);
        return getPost(3); 

    }).then(function(data){
        console.log(data);

    }).catch(function(error){
        console.log('Sorry an error ocurred!');
        def.reject();
    });   

});

Note that here I am only using jQuery’s AJAX method to do the asynchronous call to the demo API I am using that will give you back some sample JSON. You could just as easily do the above with the native XHR or even newer approaches such as fetch. As you probably already know, jQuery is an abstraction of native methods, so it makes sense that it ultimately does not matter what you use in our simple demonstration.

In the preceding example we looked at how you could implement the native Promise object if you needed a specific sequential order of the promises being returned. If you did not care at all about the order in which they came back and just needed to know when they *all* were finished you could do something like the below…

jQuery(document).ready(function() {  
    
    var test = [];

    function getPost(id){
        var def = new Promise(function(resolve, reject){
            jQuery.ajax({ 
                url: "https://jsonplaceholder.typicode.com/posts/" + id,
                type: "GET",
                dataType: "json",
                success: function(data){
                    test.push(data);
                    resolve(data)
                },
                error: function(){
                    reject();
                }
            }); 

        });

        return def;
    }

    // Implementation #2
    var arr = [getPost(1), getPost(2), getPost(3)]
    Promise.all(arr).then(function(values){
        console.log(values);
    });

});

Good stuff!

, , , ,
Share Tweet Reccomend

ECMAScript 6 Arrow Functions

Arrow functions, also sometimes called “fat arrow” functions, are a new ES6 syntax for writing anonymous function expressions. We have looked at working with ES6 in previous entries about classes and module loading. (a.k.a the “next version of JavaScript”). A function expression in JavaScript refers to the notation where a developer sets a variable equal to a function like so…

var sum = function (a, b) { return a + b; }

Note that a function expression is different from a function declaration which would look like the following…

function sum(a, b) { return a + b }

So arrow functions are primarily centered around function expressions. They have 2 main purposes. For one, they provide a more concise syntax which is a nice thing to have and can make code more readable. If were to take our function expression above and rewrite it as an arrow function, it would look like the following…

var sum = (a, b) => a + b; 

As can be seen here, this syntax looks a bit different from our original function expression. We have the arrow pointer pointing a statement that has omitted the { } from encapsulating the function body and we have omitted the “return” statement. In the above arrow function these things are implied. If we wanted to we could include these things and the meaning of the function would be the same.

var sum = (a, b) => { return a + b };

There are few rules around the syntax of arrow functions to watch out for. If there is only one argument in an arrow function the parenthesis do not need to be included. So an arrow function that simply returns “a” could be written like so…

var getVal = a => a;

However if the arrow function takes no arguments, parentheses must be used…

var getVal = () => "Hello world!";

Another interesting case of arrow function syntax is returning an empty object. The following results in an error…

var getVal = () => { };

The compiler sees this as having nothing in the function body and does not know what to return. As a result when returning an empty object you have to do the following…

var getVal = () => ({ });

So as we can see, arrow functions give us a much more terse way of writing code, allowing for a more readable concise syntax. This becomes useful in cases when using functions that have callbacks involved as arguments. Many functions that that perform asynchronous operations with data have this format. The following asynchronous promise style function…

getData().then(function (data) {
    return data;
});

Could be rewritten as the following using arrow functions…

getData().then(data => data);

It is pretty apparent that the second example is a lot more compact. As the number of functions like these get chained together, it can make the code a lot easier to read once you get used to the syntax.

Another and perhaps a more important aspect arrow functions is that they handle the scope of the “this” pointer within the function in a different manner. In other words, in arrow functions “this” points to the scope of the parent environment that the arrow function is contained within. This is a very important distinction. Arrow functions do not create their own “this” as normal functions do. A side-effect of this is that you cannot instantiate an arrow function with the “new” keyword as you can with normal functions because arrow functions have no internal prototype property.

Why were things done this way in ES6 and why is this useful? This can be very useful because you now no longer have to use apply, call, or bind to bind to the parent scope. One of the more common uses of the bind method within JavaScript applications is to pass the parent scope downward as you go multiple levels deep within methods within in object literal. For example, let’s say we had the following very general “actionClass” object literal. A lot of JavaScript applications use this pattern as an implementation…

<div class="button">Click me!</div>

<script type="javascript">
    var actionClass = {

        init: function(){
            this.setEvents();
        },
        setEvents: function(){
            // we will set events here...

        },
        doSomething: function(){
            console.log('We are doing something');
        },

        doSomethingElse: function() {
            console.log('We are doing something else');
        }

    };

    actionClass.init();

</script>

As we can see we are calling the actionClass.init() method which will set up some event handlers. So let’s add an event (using jQuery) where when we click an element we call another one of the methods within our actionClass object.

<div class="button">Click me!</div>

<script type="javascript">
    var actionClass = {

        init: function(){
            this.setEvents();
        },
        setEvents: function(){

            jQuery('.button').on('click', function(){
                this.doSomething();
            });

        },
        doSomething: function(){
            console.log('We are doing something');
        },

        doSomethingElse: function() {
            console.log('We are doing something else');
        }

    };

    actionClass.init();

</script>

This code does not work. When we try to click the div we get an error in our console…

Uncaught TypeError: this.doSomething is not a function

Why is that? Well it is because the callback function for the click event has its own scope. “this” is now pointing at the function it is being called from. One way that developers solve this is by setting a variable to the parent scope. The following code works…

<div class="button">Click me!</div>

<script type="javascript">
    var actionClass = {

        init: function(){
            this.setEvents();
        },
        setEvents: function(){

            var self = this;

            jQuery('.button').on('click', function(){
                self.doSomething();
            });

        },
        doSomething: function(){
            console.log('We are doing something');
        },

        doSomethingElse: function() {
            console.log('We are doing something else');
        }

    };

    actionClass.init();

</script>

This is certainly a viable option and works fine for our simple example. However, as we go deeper and get more complex into multiple levels of nested functions with events or getting data asynchronously via AJAX requests or any number of other possibilities the process of constantly assigning variables to the scope that you want can get kind of messy. So what other approach can we take? This is where bind comes into the picture. We could also do something like the following…

<div class="button">Click me!</div>

<script type="javascript">
    var actionClass = {

        init: function(){
            this.setEvents();
        },
        setEvents: function(){

            jQuery('.button').on('click', function(){
                this.doSomething();
            }.bind(this));

        },
        doSomething: function(){
            console.log('We are doing something');
        },

        doSomethingElse: function() {
            console.log('We are doing something else');
        }

    };

    actionClass.init();

</script>

Simply by attaching .bind(this) after our function closing bracket } we are changing the scope of the function. We longer need to say var self = this;

But with arrow functions we can accomplish the same thing without having to resort to using “bind.” We can rewrite the above in the following manner (assuming we had ES6 compatibility in the browser or we transpiled the code)…

<div class="button">Click me!</div>

<script type="javascript">
    var actionClass = {

        init: function(){
            this.setEvents();
        },
        setEvents: function(){

            jQuery('.button').on('click', () => {
                this.doSomething();
            });

        },
        doSomething: function(){
            console.log('We are doing something');
        },

        doSomethingElse: function() {
            console.log('We are doing something else');
        }

    };

    actionClass.init();

</script>

Now because we have used an arrow function, the “this” pointer is set to the parent scope because of how arrow functions bind the lexical “this” to the parent. It may take a bit of getting used to but overall the differing scope of the “this” pointer combined with the concise syntax can make code that makes use of arrow functions a lot more readable and maintainable. We will be making use of them to some degree in upcoming examples, so it was necessary to at least introduce what arrow functions are and what they do.

This is just a brief look at a couple of the newer features found in ES6. Hopefully you found it helpful.

, ,
Share Tweet Reccomend

Create Mobile Applications for iOS and Android with HTML5, JavaScript, and Apache Cordova

Obviously at the time of this writing in the 2nd decade of the 21st century, you are no doubt well acquainted with the immense proliferation and impact that mobile apps have had in and on our world. It was not long ago that we were all sitting at our computers at our desks for the large majority of the time we spent in our various avenues of technological communications over the Internet — complete with our with our giant monitors, whirring computer fans, buzzing drives, and the garbled noise of dial-up modems. Now, mobile phones and tablets probably make up as much, if not more, of our time spent working, playing, and communicating online. Everyone has a ~$100 to $600 smartphone (i.e. computer) in their pocket. And with this rise of mobile, apps found on the popular stores — like Apple’s iOS App Store, Google Play (Android), Amazon and a host of others — have completely transformed the way that we do anything and everything because well, there is an app for anything and everything. Every single facet of life probably has an app to manage some aspect of it. Need to remember to breathe? There is an app for that! Yeah, that is a joke (probably)… but there are plenty of “real” apps out there (e.g. iBeer) that are just as pointless. Fun and goofy, yes, but pointless. And they all post their pointlessness to Facebook and/or Twitter.

Whether you want to develop an app to manage some minute aspect of life or just create a fun game, or whatever else, you can download the SDK for the platform(s) that you want to release your app on, do some tutorials, and start building. That’s all well and good, but if you want to port your application to another platform (e.g. release an iOS app also for Android), you will essentially have to try rebuild the same app using the languages in tools of a different platform. For example, iOS apps for iPhone and iPad have traditionally been developed on a Mac in the Xcode IDE using the Objective-C programming language (though Apple has recently released a new language called Swift that can also be used to build iOS apps). Android apps, by contrast are built using Java and Eclipse or the more recently released Android Studio. Native Windows Phone apps are built using C# and XAML in Visual Studio. Other platforms have their own setups. If you want to take this approach you definitely can, but it should be fairly apparent that developing and maintaining a number of different codebases for multiple platforms quickly adds up to a lot of time, effort, and often money as the sizes and complexity of your apps increase.

At the same time as the rise of mobile in the past decade, something else has occurred: the rise of HTML5 and JavaScript web applications. Beginning at around 2009 – 2010 one of the more noticeable developments was the rise of websites and web applications making use of more open technologies such as HTML5 and JavaScript to bring interactivity and 2-way communication between clients (usually browsers) and servers. With Flash on the way out due its proprietary nature, resource hogging, security issues, poor SEO — along with its being snubbed by Apple for support on iPhones and iPads for basically all these reasons — meant that something had to fill the void. HTML5 and JavaScript moved into this space and developers started turning to it for creating interactive “app-like” experiences.

Wouldn’t it be awesome if there were a way to write a single application in HTML and JavaScript with a single codebase and have a way to port this application to all of the different mobile platforms? I am so glad you asked.

Apache Cordova — also commonly known as “PhoneGap” (the only difference between the two is propriety) — allows us combine combine these open technologies together with the SDKs of the various mobile application platforms to make native mobile applications using technologies such as HTML and JavaScript. You can basically create a small static HTML and JavaScript website or web application and this code will be imported into native iOS, Android, Windows Phone projects and configured specifically for the respective platforms. Thus, you *do* still have to have the SDK of the platform installed to build, run, and release the apps. So to create an iOS app you will still need a Mac and Xcode. To create Android apps you will need to install the Android SDK (which comes with the Android Studio IDE). If you don’t want to mess around with Android Studio, you can just try downloading the old standalone SDK tools here and updating from there. But the important aspect of using Cordova is that the HTML and JavaScript that each project will pull in and build will be the same across all platforms. Want to release an update with some slick new features or fix some bugs that have been reported by your users? You need only change your code in your HTML and JavaScript. You don’t have to try and rewrite the same code and/or functionality in a different language on each platform. From there all you need to do is run a few simple commands from the command lines and your HTML and JavaScript will get built and converted into an application that can run on the platform(s) you are targeting.

In what follows we will explore what it looks like to use Cordova to create a mobile application in HTML and JavaScript that can run on a number of different platform. For our examples, we will build our app for iOS and Android, but the process is essentially the same for building for other platforms (e.g. Microsoft Windows Phone, Amazon Kindle Fire). You would just need to download the SDKs for those platforms if you wanted to run your app on those types of devices as well.

Read More »

, , , , , , , , , , , ,
Share Tweet Reccomend

Local Search with RegEx

I was developing an HTML5 mobile app for an organization. The app was very simple and essentially consisted of a number of different chapters with a lot of text in each. So the homepage of the app was just a list of the chapters and each list item linked to a chapter page. All the text was in a single page (HTML document) and the app framework would just show/hide the relevant portions of it when needed. A lot of mobile HTML5 frameworks do this implementation and it essentially amounts to a simple single page application. None of the content for this app was stored on a server.

However, one of the features requested was search in that they wanted the ability to search for a term and link to the term from a search page. This is usually pretty easy if content is stored in a database because all the infrastructure to run queries against content in said database is there for you. However if all the text is in a single page application, how would you 1. find it and 2, link to it? What follows is essentially my approach in what amounts to essentially a local search functionality in a single page application.

For starters, say we had the following HTML document…

<!doctype html>
<html>
  <head>
    <title>App</title>
  </head>
<body>
    <div id="home" class="page">
        <ul id="menu" class="page">
            <li><a href="#search">Search</a></li>
            <li><a href="#chapter1">Chapter 1</a></li>
            <li><a href="#chapter2">Chapter 2</a></li>
            <li><a href="#chapter3">Chapter 3</a></li>
        </ul>
    </div>
    <div id="chapter1" class="page">
        <p>The quick brown fox jumped over the lazy dog.</p>
        <p>How now brown cow?</p>
        <p>Something else</p>
    </div>
    <div  id="chapter2" class="page">
        <p>Chapter 2 text here...</p>
        <p>More text here...</p>
    </div>    
    <div  id="chapter3" class="page">
        <p>Chapter 3 text here...</p>
        <p>More text here...</p>
    </div> 
    <div id="search" class="page">
        <input id="search-box" type="search" />
        <ul id="search-results"></ul>
    </div>   
</body>
</html>

Each div with the class “page” would be loaded into the main view when a user clicked on a link to the id of the <div> as can be seen in the menu page. For brevity, I’ve kept the content of each <div> really small but imagine that there were a number of chapters and each paragraph in each chapter had large amounts of text.

What I ended up doing is I added a class called “indexed” (to say that the content of this element is going to be indexed in the search functionality) and some “data-reference” attributes to each paragraph of text to be able to tell where in the application I was. If we were going to have for text *with links*, we’d need to have a way to tell “where we are” so that when we load that page we could scroll to the div that had the text that was searched for.

<!doctype html>
<html>
  <head>
    <title>App</title>
  </head>
<body>
    <div id="home" class="page">
        <ul id="menu" class="page">
            <li><a href="#search">Search</a></li>
            <li><a href="#chapter1">Chapter 1</a></li>
            <li><a href="#chapter2">Chapter 2</a></li>
            <li><a href="#chapter3">Chapter 3</a></li>
        </ul>
    </div>
    <div id="chapter1" class="page">
        <p class="indexed" data-reference="1-1">The quick brown fox jumped over the lazy dog.</p>
        <p class="indexed" data-reference="1-2">How now brown cow?</p>
        <p class="indexed" data-reference="1-3">Something else</p>
    </div>
    <div  id="chapter2" class="page">
        <p class="indexed" data-reference="2-1">Chapter 2 text here...</p>
        <p class="indexed" data-reference="2-2">More text here...</p>
    </div>    
    <div  id="chapter3" class="page">
        <p class="indexed" data-reference="3-1">Chapter 3 text here...</p>
        <p class="indexed" data-reference="3-2">More text here...</p>
    </div> 
    <div id="search" class="page">
        <input id="search-box" type="search" />
        <ul id="search-results"></ul>
    </div>   
</body>
</html>

So as the user types into the search box if we use some jQuery and some RegEx we can 1. search through every “indexed” element for the text that was searched for and 2. populate the search results <div> with links to the various elements. It would look a little bit like this…

jQuery(document).ready(function(){

    function search(searchedText) {
        if(searchedText.trim() === ""){
            jQuery('#search-results').empty().text('No results...');
            return;
        }

        var res = jQuery(".indexed:contains('"+searchedText+"')").each( function() {
            var current = jQuery(this).closest('div[class="page"]');
            var regex = new RegExp(".{0,20}" + searchedText + ".{0,20}", "i");
            var str = jQuery(this).text().match(regex);
            var ref = jQuery(this).closest('[data-reference]');
            jQuery('#search-results').append('<li><a href="#'+ current.attr('id') +'?reference='+ ref.attr('data-reference') +'">... '+ str +' ...</a> - '+ current.find('h1').text() +'</li>');
            return; 
        });

        if(res.length === 0) {
            jQuery('#search-results').empty().text('No results...');
        }
    }

    var searchResults = jQuery('#search-results'), searchTimeout;

    jQuery('#search-box').on('keyup', function(){
        var el = jQuery(this);
        searchResults.empty();
        clearTimeout(searchTimeout);
        searchTimeout = setTimeout(function() {
            search(el.val());
        }, 1000);
    });

});

So basically what we are saying here is that while we type into the search box, we will wait until the user is finished typing and then we will check each “indexed” element for the text we are searching for. If we find it we will create a link to that text to the chapter and append a query string value to the “data-reference” value of the element that contains the text. We can then use the event that fires every time the page changes (as a lot of mobile frameworks have) to check for this reference parameter in the url. If it is there we can do something like the following to scroll to the paragraph that contains the text we were searching for. We call the following scrollTo function on each change/load of a page.

function getParameter(name){
    var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location);
    return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}

function scrollTo() {	
    if(getParameter('reference')) {
        jQuery('html,body').animate({
            scrollTop: jQuery('[data-reference="'+ getParameter('reference') +'"]').prev().offset().top -20
        }, 100);            
    }
}

The way things are set up at the moment, the regular expression will search for the exact text entered into the search box. Thus, search is case-snesitive at the moment. No matter. If we wanted to incorporate case-insensitivity into things we could simply add the following method…

// make :contains case insenstive for search
jQuery.expr[":"].contains = jQuery.expr.createPseudo(function(arg) {
    return function( elem ) {
        return jQuery(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
});

By implementing these sorts of techniques and methods, you can incorporate local search and linking into a single page application with a relatively small amount of code. You could take this and expand upon it pretty easily. So even within the perceived limitations of a single page application, you can find ways to implement dynamic functionality that you would expect from any other application. Until next time, happy searching!

View Demo
, , , , ,
Share Tweet Reccomend

jQuery Event Delegation

Event delegation is a very important part of writing efficient code for handling events in JavaScript. We looked at JavaScript events in this section here and looked at some other components of it when exploring things like the publish/subscribe pattern in creating JavaScript event channels.

What is event delegation? Well, in general the concept of event delegation could be thought of as assigning a single event handler to handle multiple items.Event delegation is not necessarily a requirement for handling JavaScript events, but it certainly is a good practice and a good habit to apply to your JavaScript code.

We’ll take a look at this below using jQuery in our example. Let’s say we had a simple menu like the following.

<!DOCTYPE html>
<head>
    <title>Event Delegation jQuery | 9bit Studios</title>    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
    <div id="menu">
        <a href="#">Home</a>
        <a href="#">About</a>
        <a href="#">Portfolio</a>
        <a href="#">Projects</a>
    </div>          
</body>
</html>

So how would we add events to our <a> elements? Certainly we could do something like the following…

<!DOCTYPE html>
<head>
    <title>Event Delegation jQuery | 9bit Studios</title>    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
    <div id="menu">
        <a href="#">Home</a>
        <a href="#">About</a>
        <a href="#">Portfolio</a>
        <a href="#">Projects</a>
    </div>

    <script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery('#menu a').on('click', function(e){ 
            console.log(e.target);
        });    
    });
    </script>  
          
</body>
</html>

In doing this, we have added events to each of the individual <a> elements. While this certainly works it becomes a bit messier when you start to dynamically add elements to the DOM. In modern web applications, dynamic, interactive, client-side updating of content is certainly a very common implementation that you come across. Let’s say we wanted to add a button to dynamically add new items to our menu…

<!DOCTYPE html>
<head>
    <title>Event Delegation jQuery | 9bit Studios</title>    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
    <div id="menu">
        <a href="#">Home</a>
        <a href="#">About</a>
        <a href="#">Portfolio</a>
        <a href="#">Projects</a>
    </div>
    <a id="addNew" href="#">+ Add New Menu Item</a>

    <script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery('#menu a').on('click', function(e){ 
            console.log(e.target);
        });  
        jQuery('#addNew').on('click', function(e){ 
            var html = '<a href="#">New Item</a>';
            jQuery('#menu').append(html);
        });    
    });
    </script>  
          
</body>
</html>

When you add a few new menu items what happens when you click on the newly created items? Nothing. Why is that? Because when we ran our code to add the events to each individual <a> elements those newly added elements did not exist (and thus never got event handlers attached to them).

What could we do to solve this? Well, we could certainly run the code to add event handlers again, but as our codebase gets bigger and more complex handling things this way gets a bit on the messy side.

What should we do then? As it turns out a better way to approach this is to add the event to something that will always be there and won’t change. In this case, it’s our <div id=”menu”> container. By adding the click event to the this container, it servers as the delegate for all of our <a> elements. We can then do the following…

<!DOCTYPE html>
<head>
    <title>Event Delegation jQuery | 9bit Studios</title>    
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
    <div id="menu">
        <a href="#">Home</a>
        <a href="#">About</a>
        <a href="#">Portfolio</a>
        <a href="#">Projects</a>
    </div>
    <a id="addNew" href="#">+ Add New Menu Item</a>

    <script type="text/javascript">
    jQuery(document).ready(function(){
        jQuery('#menu').on('click', 'a', function(e){ 
            console.log(e.target);
        });  
        jQuery('#addNew').on('click', function(e){ 
            var html = '<a href="#">New Item</a>';
            jQuery('#menu').append(html);
        });    
    });
    </script>  
          
</body>
</html>

Notice the syntax of displaying the a selector after the. As is described in the jQuery docs for the .on() method

If selector is omitted or is null, the event handler is referred to as direct or directly-bound. The handler is called every time an event occurs on the selected elements, whether it occurs directly on the element or bubbles from a descendant (inner) element.

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

So now what happens when you click on a newly created <a> element in our menu. Voila! The event is captured. Huzzah! We now never have to worry about adding (or removing) any events for our dynamically created elements because we have used event delegation to handle it for us. A single function takes care of all future updates. It’s a one and done kinda thing.

Hopefully, this discussion has helped you better understand what event delegation is and where it might be useful. Until next time, happy delegating!

, ,