5 Minute JavaScript #14: forEach

After discussing how to create a range in the last post, we will discuss some of the array methods and how to use them to make your code more readable and concise.

First of all, I want to add that every array method uses the callback pattern. We’ll do a post on this pattern later, when discussing Asynchronous JavaScript, but for now you need to know that callbacks in these functions are called for every item in the array.

The easiest array method is called forEach and will just iterate over every item in the array.

	[1, 2, 3].forEach(function (item) { console.log(item); });

Most people will recognize this method. It iterates over every item and does nothing with the return value you provide. What most programmers don’t know is that you have some additional features in forEach.

	[1, 2, 3].forEach(function (item, index, array) { this.log(item);  }, console);

The forEach function lets you set the functions context (= this, more later) as well. In the previous example I injected console as the ‘this’ value in callback function.

But beware:

	function hasNumber (arr, number) {
		arr.forEach(function (item) { 
			if (item === number) return true; 
		});
	}

While this code might look okay, you must know that JavaScript’s forEach is still a callback function. Returning the value true inside the callback won’t result in the global function (hasNumber) to return true. You should refactor this code to

	function hasNumber (arr, number) {
		var found = false;
		arr.forEach(function (item){ if (item === number) found = true; });
		return found;
	}

By using the some-method you will get an even easier result, but more about that in a future post.

OGh APEX World 2015

DSC_9284-001 (800x533)

iAdvise Diamond Sponser APEX World 2015

After 5 successful earlier editions of the APEX World day, they chose a different venue for the 2015 edition. The ship SS Rotterdam was the setting for the annual APEX World event. For us, it was not only the location that was special, we were also official Diamond Sponsor of APEX World 2015! And a great day it was! Not only to meet a lot of nice people from the Benelux APEX community, but also for the great sessions that have provided us with a lot of inspiration for the upcoming period. It was really an honour for us to be the Diamond Sponsor this year.

 

Like previous years, the day started with a short opening. This year, Reinier van Grieken, vice president and managing director of Oracle Netherlands was invited to do the opening. He emphasized that the OGh did a great job by welcoming such an enormous audience, which continued to grow over the past 5 years (more than 400 visitors this year).

In this overview we will take you aboard the SS Rotterdam on the 25th of March, so if you missed it, you’ll still get the highlights. And if you were there, you can look back on a great day.

 

Keynote: OraEvents – Stijn van Raes (iAdvise) & Yves van Looy (Oracle Belgium)

Stijn van Raes at APEX World 2015

Stijn van Raes at APEX World 2015

In an entertaining presentation the speakers told us about how Oracle and iAdvise created the situation of a supplier – customer – supplier – customer. iAdvise was hired to build the OraEvents application for Oracle (www.oraevents.eu). The architecture of this application makes it possible to collect data about the interests of registered users. In some situations this can be a huge advantage. For example, there was a situation when Oracle organized an event but it was really hard to get enough attendees. Oracle Belgium searched in the database of OraEvents and in half an hour they filled up the event.

At the end of this keynote, iAdvise wondered what could be possible features in future APEX versions (like  APEX 6, APEX 7 or even later). Thoughts about single page web applications, Node.js integration and Source Control were brought to attention. iAdvise hopes that the APEX community will think about these possible features and bring over these ideas on  https://apex.oracle.com/vote or the newly formed linkedin group http://goo.gl/L9DirJ

 

APEX suitable for high volume environments – PostNL & Fiton

Fiton and PostNL developed an application to process postal orders in a very easy and quick manner. Not only national but also international orders can be handled with this system.

Basic and simple APEX functionality was used to enter barcodes in a system which looked like some kind of wizard. Only 4 APEX pages were developed, besides a login system. The application was based on Theme 13 in APEX. The part of the system that takes care of printing invoices was built as a Java applet. The philosophy of this client case was: “Less is more”. Keep your application as simple as possible.

 

Oracle Forms to Oracle Application Express migration – iAdvise (Yvonne van Dorst) and Robeco (William de Vries)

Robeco decided to migrate 7 applications which had been developed with Oracle Designer. These applications have to be compatible with at least an Oracle 11g database and will need to have a distinct corporate identity. APEX turned out to be the best tool. In the beginning Robeco and iAdvise started to migrate 3 applications with the intention of migrating 4 more applications in the future. For Robeco it was very important to use one template for all applications. This could be realized by an APEX theme developed by iAdvise based on bootstrap in combination with a JavaScript framework.
All 7 APEX applications were developed in a period of 3 months. The business has become APEX minded and almost all questions are more or less like: “Can we do this in APEX?” The answer in most cases is: “Yes we can!” Robeco is a very satisfied APEX customer.

 

Design of good-looking, flexible and responsive applications – iAdvise (Menno Hoogendijk) and Twinq (Laurens Hamelink)

Twinq develops software for co-operations of owners of apartments. People who use this software will do this on several devices like a desktop (24 inch), a tablet (10 inch) or smartphone (5 inch). Twinq’s vision is that software has to be sexy and good-looking. To make this kind of software for all types of devices, iAdvise and Twinq used bootstrap. The APEX application uses AJAX and javascript, but all in favor of usability. Besides this, the applications are equipped with the possibility to use keyboard shortcuts.

At the end of this presentation, the audience was asked to visit an online vote, just like tinder. They could indicate whether they really experienced the demo as “Sexy Software” or not. More than 80% was convinced of the sexiness of the software.

 

Hidden Nuggets in Application Express 5.0 Page Designer – David Peake (Oracle US)

Everyone knows that APEX 5.0 has a lot in store for us. In this presentation, David Peake took
us through the new page designer and told us his favorite features.

The page designer is now divided in three sections. The old tree view can be consulted on the left side of the screen.

The middle section consists of a wide grid layout where we can easily drag and drop new items to our page. Messages will show you what is missing for the new created items.

In the right section we can directly see and edit the properties of the selected item. This new interface allows us to develop much more efficiently. Besides editing one item at a time, it is now possible to edit multiple items. This will save us a lot of time, for example when you want to change the template of all your labels. And when the latest adjustment to your page does not meet your expectations, you can now undo and redo it by simply pressing a button.

Not only the grid layout is quite convenient, keyboard shortcuts will soon be our best developing buddies. To help us along the way, help texts and search capabilities have been increased considerably. Now we will lose less time, if we are looking for that one particular item.

The page designer will give us the possibility to develop even faster!

 

Interactive Reports: Watch out for the Pitfalls! – Peter Raganitsch (FOEX (AT))

In APEX, we’ve got two different report types to work with: Classic and interactive reports. Many developers prefer the interactive report, because the user can change the appearance of the data through several manipulations. This means that the query behind this report is also adjusted. To figure out how the query will look like after a few filters, you can use the debug function. To get the full query available in logging, you must replace the ‘YES’ with ‘LEVEL9’ in the url. This gives you a more detailed logging. You can also add a small PL/SQL code in the application properties (Security, Database Session, Initialization PL/SQL code):
“APEX_DEBUG.enable (9) ;”. Remember after testing to remove it again.

The pagination type also affects the query of your report. If you use the type ‘X to Y of Z’, then the query will be extended to return the total number of rows. Therefore, use the type ‘X to Y’ for reports with many records.

Also, there is a very useful package for interactive reports named APEX_IR. This can be used to see the full runtime query of your interactive reports, add filters, clear or reset the report settings, delete saved reports and manage subscriptions.

Version 5.0 has several enhancements on interactive reports. Henceforth, it will be possible to use multiple interactive reports per page. Besides that, the action region – after selecting an option in the action menu – will be showed in modal dialogs instead of above the report. The menu is also expanded with the pivot function and the end user can now do a group by on a maximum of eight fields instead of five. With all these improvements, version 5.0 will be very well received by both, developer and end user.

 

A Spotlight on the Smaller Features of APEX 5 – Dietmar Aust (Opal Consulting (DE))

After three early adopters and a pre-production version of APEX 5, everyone nowadays knows about the most important and biggest new features of APEX 5. But what about those features you don’t notice immediately? Dietmar Aust took us through some of those features during his session about the smaller features of APEX 5.

One of the functional improvements Dietmar told us about is: the file storage. In the past apex versions there were no relative file paths, you had to upload your files individually and updating your files took a lot of time. In the new file storage you do have relative file paths and there is the possibility to upload zip files that will be extracted into the correct folders. Updating your files can be done this way too. Also after updating your files you’ll notice at runtime that the version number, which you can find in the url referencing your files has changed to avoid caching issues.

Another runtime engine improvement is the extended substitution syntax where you can now define different escaping modes. For example: if you use a dynamic action that creates a JavaScript alert to show an application item like ‘&P1_ITEM.’. In this case, cross site scripting can be applied. To avoid this there is now the possibility to escape JS syntax by defining the application item like this: ‘&P1_ITEM!JS.’.  There are a few more escaping options that can be used. These can be found in the slides that you can download from Dietmar Aust’s blog (http://daust.blogspot.be/2015/03/slides-from-my-presentation-at-apex.html) like all other improvements that have been discussed in the session.

 

Keynote: Elegance in the Enterprise – Shakeeb Rahman (Oracle US)

On every project I’ll try to surpass my previous creations in usability and design. And every time I’ll spend some time analyzing the most popular websites about their latest user interfaces and the way they interact with the end user. How do they present their navigation? Where do they put the buttons? And how do they organize their content on a page? All these questions are important because you want your users to feel comfortable when they use your application.

This keynote felt like a spring breeze on the – maybe a little bit – too hot SS Rotterdam. It was refreshing to see the amount of dedication, consideration and research the APEX design development team put in their Universal Theme. Shakeeb Rahman brought a lot of liberating facts about the way users interact with web applications to our attention. One of the statements that caught my attention was:

Most users put a higher rate on an application after the design is improved because they believe it works better than the old one.

Shakeeb also told us to think twice before using reports. Because in some cases it may not be the best approach for presenting the data to the end user. Sometimes it’s more efficient to use a diagram or a chart because users instantly see how your data it related. And if using a report still is the best approach, try to eliminate the columns users don’t really need to see right away. Minimizing the amount of data on a screen results in faster reading and, in that way, is more efficient.

Another thing to reflect on when building your application, is to split the contents into smaller bits by grouping similar fields. By dividing your contents, users don’t see your page as a big chunk of data,  but more like smalls pieces of useful information.

The new built-in template that comes with APEX 5 results in easy-to-create, smart, responsive web applications because APEX has done the research for you. It uses built-in crisp icons and follows the currently hot “flat design trend”. Now it’s not only faster to create user friendly web application it’s also much easier because they put all the know-how about user interaction in the new and improved application builder.

That’s also handy because now you can take a peek at how APEX pages are designed if you’re looking for inspiration instead of googling around the web like I used to do before.

iAdvise consultant at APEX World 2015

iAdvise consultant at APEX World 2015

5 Minute JavaScript #13: How to create an array from a range

Previous blogpost we discussed extending native data types in JavaScript. Today we’ll create a method in the array prototype that you can use to easily create a range such as an array.

Some programming languages allow you to easily create an array from a range, such as:

Scala

	val list = 0 until 10 toList

or Ruby

	arr = [0..10]

In JavaScript however, you need to use a for-loop to fill an array with ranged values. You could create a function that returns a filled array based on a from and to value like this:

function fill (from, to) {
 var a = [];
 for (var i = from; i <= to; i += 1) {
   a.push(i);
 }
 return a;
}

But then you have declared a function fill globally; that doesn’t really say much… it would be syntactically more interesting to use the Array prototype like this:

Array.prototype.fill = function (from, to) {
 var a = [];
 for (var i = from; i <= to; i += 1) {
   a.push(i);
 }
 return a;
};

Now we can create a new array using a very simple syntax

	var arr = [].fill(1,5); // results in [1,2,3,4,5]

While not perfect, defining the fill function this way, is a lot more readable. You start with an empty array and you fill it with a range of values. This makes perfect sense.

Google’s Polymer and Paper Elements

Polymer

An interesting take on web future at Devoxx 2014 was Polymer. This framework is build on top of the HTML Web Components specification. It allows you to create your own HTML elements. These elements have their own element-contained HTML (called shadow-dom), private CSS for styling and even some JavaScript for the user to be able to interact with the component.

One example of a useful way to use your own HTML element is the Google Maps widget. Normally we should import the JavaScript source (functionality), create a div with a certain ID, and then initiate the map by selecting the HTML element that represents the map. With the Web Components specification, Google was able to create a <google-map>-element that does all that for you. The only thing you need to do is import the element (which contains element, styling and functionality). Making your code more readable.

Paper elements

In a previous blogpost we mentioned the style guidelines for Material Design. Google also implemented these guidelines in Polymer, giving you a range of new HTML Web Components that follow the Material Design guidelines. This HTML extension is called Paper elements and is easy to install and use.

Installing Polymer and Paper elements

Using Bower, we can easily install Polymer and Paper elements, but you can also download the ZIPs on the polymer website.

bower install --save Polymer/polymer
bower install --save Polymer/core-elements
bower install --save Polymer/paper-elements

After installing, you will see that all the new HTML elements are added to the bower_components folder in your application.

Using core and paper-elements

First of all, we will need to include the polymer.html script to make sure that everything runs on legacy browsers supported by Polymer. Also a main.css file can be useful to style the added elements.

<!doctype html>
<html>
    <head>
        <meta charset="utf-8">
        <title>polymer blogpost</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width">
        <script src="../bower_components/polymer/polymer.html"></script>
        <link rel="stylesheet" href="styles/main.css">
    </head>

<body>

</body>
</html>

Next, we will need to import some core-elements to create a nice looking app. For this example we will use core-toolbar, paper-icon-button, and paper-progress.

We can import these elements by adding a link to the html page’s HEAD section.

<link rel="import" href="../bower_components/core-toolbar/core-toolbar.html">
<link rel="import" href="../bower_components/core-header-panel/core-header-panel.html">
<link rel="import" href="../bower_components/paper-icon-button/paper-icon-button.html">
<link rel="import" href="../bower_components/paper-progress/paper-progress.html">

Now we can start using the new HTML elements, but first of all we need to add some attributes to the body tag. To make sure that the layout is displayed correctly we need to add: fullbleed (makes sure there are no more margins and paddings), layout (makes sure body takes up 100% of the screen), and vertical (makes sure the layout is vertically flowed).

<body fullbleed layout vertical>

</body>

Now that we got the body out of the way, we will need to add the toolbar to our application. We’ll add a nice looking menu button to the left of the application’s name.

<body fullbleed layout vertical>

        <core-toolbar>
            <paper-icon-button icon="menu"></paper-icon-button>
            <div>MY APP</div>
        </core-toolbar>

</body>

This will show us a nice looking toolbar with our application name (originally called MY APP). The button on the left of the title has the fancy ripple effect when you click on it (as described in the Material Design guidelines). but we can do more than that. For example we can add a progress bar to this toolbar. We can even make it fit and stick to the bottom.

<body fullbleed layout vertical>

        <core-toolbar>
            <paper-icon-button icon="menu"></paper-icon-button>
            <div>MY APP</div>
            <paper-progress class="bottom fit" value="30"></paper-progress>
        </core-toolbar>

</body>

The result looks somewhat like this

Polymer, Paper elements ExampleThis looks and feels already like a native mobile application and we didn’t have to style anything. Everything has been done with real HTML Elements, which makes the code very readable and easy to maintain.

For more examples and guides for creating your own polymer / paper elements application goto the polymer website.

5 Minute JavaScript #12: extending native functionality

In the previous blogpost we took a quick look at the prototype of a value in JavaScript. We also noted that primitive data types such as String and Object have prototype objects of their own. JavaScript allows you to extend these prototype objects with.

A useful example is to add formatting functionality to the String prototype. JavaScript does not have a format function on String, even though this functionality is very useful. So, let’s add it ourselves.

String.prototype.format = function () {
   var str = this;
   for (var i = arguments.length - 1; i <= 0; i -= 1) {
       str = str.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
   }
   return str;
};

Now we can format strings like this

var template = 'Hello {0}, my name is {1}!';
var receiver = 'Tom';
var sender = 'Steve';
console.log(template.format(receiver, sender));

We can also rewrite functionality that we don’t like. For example, remember the time everyone debugged JavaScript with alert? People still tend to do this just because they are used to doing it. Even some frameworks are intrusive enough to show you an alert message when you make an error. That’s not really something we want. We can overwrite the alert functionality on the window object because… why wouldn’t we?

window.oldAlert = window.alert;
window.alert = function(message){
   // check if console exists
   if (typeof console === 'object') {
       // logs the alert instead of showing it
       console.log('[ALERT] '+message);
   } else oldAlert(message);
};

However, always make sure that you keep a reference to the old implementation!

Google’s Material Design

At Devoxx 2014, a large amount of presentations involved Google’s Material Design and Polymer. Before we dive into Polymer, it might be useful to have a look at some of the design guidelines proposed by Google. These guidelines are bundled into a style guide, named Material Design.

What is Material Design?

Material Design is a set of guidelines that are useful for modern designers. These people are challenged with the daunting task to create a design that not only targets desktops, but also the web and mobile devices. These are totally different applications, sometimes being developed by different teams. To make the user experience intuitive and consistent over these multiple platforms, a strict set of rules need to be defined.

Google’s Material Design consists of two components: material and motion. The material component provides context in design. It’s the surface and elements that are visual to the user. Material also acts in a certain way. For example, material can cast shadows. These real-life properties of materials are included in the guidelines for an intuitive look and feel.

The motion component makes sure that there is some kind of continuity in your product. Animations are supposed to give meaning to your actions. The user experience should be fluent and uninterrupted.

material-design-1

Material

In material design, material has a lot of properties. First of all you will need to grasp that material design is a 3D world that is displayed in 2D. Each material and component has a width, height, but also a thickness (1dp). This thickness allows the material to cast shadows, and by animating these shadows, the designer can make the 2D material move over the z-axis.

material-design-2

Guidelines for color and typography will make your important content stand out. It will allow the user to make a bold statement.

material-design-3

Components

Material design not only shares guidelines for high level principles, it also defines guidelines for specific components. Google also implemented these guidelines in an open source framework called Polymer. We’ll have a closer look at some of these components.

Buttons

There are three different types of buttons. The most iconic one is the Floating Action Button (or FAB short). This is a button that represents the most logical action in the current context (for example: the add-functionality when you are in a calendar application).

material-design-4material-design-5material-design-6

Cards

This material can be used as a viewport and as a dialog. You can make a collection or grid of cards in your applications to show a more visual type of list.

material-design-7

Lists

Material Design also covers lists. A list consists of a single continuous column of sub-divisions of equal width called rows. These rows hold content and can vary in height. These lists are best suited to display a homogeneous data type or sets of data types.

material-design-8

Conclusion

Google’s Material Design is a goldmine when you are looking for modern design information that is applicable across different platforms (mobile/web/desktop). The comprehensive guide is a must read for everyone that are developing layouts and designs.

The properties of material and motion reflect the realistic world and that’s why these interfaces look and feel so intuitive. Being optimized for touch, these designs are set for the future.

If you are looking for an example application that uses the guidelines of material design, Google’s example quiz-app topeka is a great showcase for Material Design, Polymer and Paper Elements.

5 Minute JavaScript #11: Prototypes

Last week, we discussed the JSON format. Today we are going to take a deeper look in the object structure in JavaScript. In most object-oriented programming languages you have some kind of classical inheritance. This means that the language allows you to define a sort of blueprint of an object named a class. JavaScript doesn’t work with these concepts. Instead, it works with prototypes. The dynamic nature of JavaScript allows you to apply inheritance on object level instead of class level. Every object has a prototype object, you can set this prototype object and automatically you will be able to access properties or functions on the child object.

var parentObject = { x:1, y: 1 };
var childObject = { x: 2, a: 2 };
childObject.prototype = parentObject;

In the example above, the childObject has three properties: x, y and a. Whenever JavaScript is interpreted, the interpreter selects the first instance it finds of a property/function. So if we would look for the property x on childObject, we would find 2 instead of 1 because the childObject’s x definition is the first one the interpreter encounters.

In JavaScript native types also have a prototype object. That prototype contains all the methods you can use on the type. For example the String type has a prototype object that contains the following methods:

  • String.prototype.charAt()
  • String.prototype.slice()
  • String.prototype.trim()
  • String.prototype.split()
  • String.prototype.toUpperCase()

These prototype methods are easy to use, you can just call them from the object, e.g. “lowercase”.toUpperCase(). Not only the String type has these methods, also Object, Array, Number and even Function!

var char = 'my string'.charAt(0);

We use these prototype functions every day and the fun thing is that we can create our own. But that’s for the next blogpost.