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

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!

, ,
Share Tweet Reccomend

JavaScript Extend

One of the most important parts of any programming language is the ability to extend objects, creating your own objects and objects that inherit from those objects. In class-based languages like Java or PHP you’ll see the “extends” keyword being used to set up inheritance between different objects.

JavaScript, however, is structured quite a bit different than class-based languages because it is a prototype-based language. For a more detailed look at JavaScript inheritance see this article here. Additionally, opposed to having different types assigned to variables, in JavaScript everything is an object (and, as a result, everything can be extended)
.
In what follows we’ll take a brief look at JavaScript extend functions. Note that this is a little bit different than inheritance. Extend functions in JavaScript could maybe be thought of merging 2 objects, rather than one object inheriting from another. We’ll refer to these as the target object and an extending object. Remember in JavaScript that an object literal is essentially a collection of key/value pairs. Recall too that in JavaScript object keys can also have functions for their values as well. So if a “key” in our extending object already exists on the target object the value for the key in the extending object will overwrite the value for the key in the target object.

The function to extend an object will look something like what is below…

function extend(targetObject, extendingObject){
    for(var key in extendingObject) {
        targetObject[key] = extendingObject[key];
    }
}

Let’s take a look at how this works in practice. Say we have an object called “robot,” that has a couple of properties…

var robot = { 
    size: 'small',
    gas: 100,
    mode: 'helpful',
    move: function() {
        console.log('Walk')
    }
};

Now let’s say we want to extend our robot with some “upgrades”. New properties (keys) will be added to the object and existing properties will overwrite the values for the current object. Will give the robot some more gas (overwriting the robot’s current value), and give it a new mode (setting) and give it a rocket launcher,

var upgrades = {
    gas: 200,
    mode: 'crush kill destroy',
    rocketLauncher: function(){
        console.log('BOOM');
    }
};

Pass this into the extend function…

extend(robot, upgrades);

And now our robot object looks like the following…

var robot = { 

    size: 'small',
    gas: 200,
    mode: 'crush kill destroy',
    move: function() {
        console.log('Walk')
    },
    rocketLauncher: function(){
        console.log('BOOM');
    }
};

Now that we’ve set our robot to “crush kill destroy” it’s a good thing we’ve kept the size at “small.” Hopefully it will be easier to take out if it turns on us.

Let’s take a look at the popular Underscore.js libary’s extend function…

_.extend = function(obj) {
    each(slice.call(arguments, 1), function(source) {
        if (source) {
            for (var prop in source) {
                obj[prop] = source[prop];
            }
        }
    });
    return obj;
};

Aside from a little bit of conditional checking and variance in how it’s called, the core functional purpose is essentially the same as the function we wrote above.

You’ll often see the extend function used to pass in different options or settings when calling certain jQuery plugins.

$(window).load(function() {
    $('.flexslider').flexslider({
        animation: "slide",
        animationLoop: false,
        itemWidth: 210,
        itemMargin: 5,
        minItems: 2,
        maxItems: 4
    });
});

Within the plugin there will be some default settings, but an object literal can get passed in when calling the jQuery plugin that will overwrite the default settings by using the jQuery extend function. This is an easy way to implement custom settings for a jQuery plugin.

So as we have seen, extend functions in JavaScript are a common and useful way to merge two objects together for a variety of purposes. Hopefully you’ll be able to use this when writing some of your JavaScript based applications.

, ,
Share Tweet Reccomend

AJAX and WordPress

When the web moved from HTML4 to HTML5, the rise of AJAX based web applications came along with it. AJAX (which stands for Asynchronous JavaScript and XML) can mean a number of things but in practice it often refers primarily to the client/server interaction where JavaScript can be used to communicate with a server by making calls at various times under various conditions to send and receive data. This can be happening as often as you like in real-time without the user having to navigate to another webpage or refresh their browser (i.e. asynchronously).

AJAX

What is an example of this? Well, say I wanted to put a stock ticker on my webpage or in my web application. I could use JavaScript to make a call to a service like some stock-market API that will give me quotes on a particular stock, get the data back, and display it in the UI in a visually appealing manner. As these market prices update over time, I can periodically update the quotes that I’m displaying on the page. The format that the server returns data in really depends on the service you are calling. It can often be be XML (as the X in AJAX suggests) but another popular format is JSON. I actually like JSON a bit better, myself. The experience of parsing through everything in code just seems a bit cleaner so if there is the option to have the data you are trying to get returned to you in JSON, I’ll usually opt for that.

Because JavaScript is such a universally cross-platform language capable of running on so many different devices in different environments, this can be a great way for different applications to communicate with each other. The result, hopefully, is to give your users the best experience possible whether they are on desktop, mobile, tablet, or some other crazy device.

In the early part of the 21st century, something else that was and has been absolutely ubiquitous across the internet is WordPress. From it’s humble beginnings of being exclusively web-based blog software, it has transformed into essentially the most popular content management system (CMS) used for running small and medium sized websites or web applications.

In what follows, we can look at how we can undertake merging these 2 things together. We’re basically going to look at how we can send and receive JSON data to a WordPress database and read from and write to the tables within WordPress using AJAX.

Read More »

, , , ,