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!
asynchronous,
JavaScript,
jQuery,
promises,
web developmentPreviously, we looked at getting set up creating a React “to do” application by installing our Node.js driven build tools and laying out some introductory components of code. In what follows we will continue on where we left off.
Adding “To Do” Items & Handling User Input
So far we have just looked how to display our components. Rendering data out to our page is all well and good, but to make our application truly dynamic we are going to need to implement a way to add and remove items to and from our list as well as edit them should we need to make any changes to any of the properties. So let’s update the code in TodoList.js to the following…
import {react} from 'react';
import {Todo} from './Todo';
export class TodoList extends React.Component {
constructor(){
super(...arguments);
this.state = {
todos: this.props.data,
addTodoTitle: '',
addTodoSummary: ''
}
}
addTodoTitleChange(e){
this.setState({
addTodoTitle: e.target.value
});
}
addTodoSummaryChange(e){
this.setState({
addTodoSummary: e.target.value
});
}
addTodo(){
this.state.todos.push({
id: this.state.todos[this.state.todos.length - 1].id + 1,
title: this.state.addTodoTitle,
summary: this.state.addTodoSummary,
done: false
});
this.setState({
todos: this.state.todos,
addTodoTitle: '',
addTodoSummary: ''
});
}
render() {
var items = this.props.data.map((item, index) => {
return (
<Todo key={item.id} title={item.title} summary={item.summary} completed={item.done} />
);
});
return(
<div>
<ul>{items}</ul>
<h3>Add New Item:</h3>
<label>Title</label> <input type="text" value={this.state.addTodoTitle} onChange={() => this.addTodoTitleChange()} />
<label>Description</label> <textarea value={this.state.addTodoSummary} onChange={() => this.addTodoSummaryChange()}></textarea>
<button onClick={() => this.addTodo()}>Add New Item</button>
</div>
)
}
};
So let’s discuss what is going on here. We have added 2 new values to our initial state object and we have created a form that will allow us to add a new “to do” item to our list. When we enter text into these fields the functions to update the state will run and we will update these values with setState by getting the current value of the form element we are editing off of the event that is passed into the function (e.target.value). Once we have filled out the form with the title and summary of the new item that we want, we can click the “Add New Item” button which, as we can see from our “onClick” handler, will run the “addTodo” function. If we look at this function we can see the code that we will need to add a new item to our list. Recall that we have to give each individual item an id and no two items can have the same id. So to generate a new id we will look at what the id value of the last item in our array is and just add 1 to that. That is an easy way to ensure that the new items that we add are always unique. We get the title and the summary from this.state which we have been setting in our text input handler functions. Lastly, we just set the initial value of the “done” flag to false since adding a new to do to the list is presumably not done yet. All of this data is passed into the common JavaScript Array object’s “push” method. We then update the state of our “todos” and then clear out the input text box and textarea in our form to get them ready to receive another value.
So build your code with $ webpack (or whatever task runner you are using) and try it out. You can see how we can now add new items to our list! Pretty slick!
Improving Our Code
Our example above works but you may have noticed something problematic with our implementation. We have individual handler functions for the two text elements in our “Add New Item” form. We also have separate properties that we use for setState. This is fine for this simple example, but what if we had a component with many different properties and values with many different fields that needed to be filled out? If we were to take the same approach as our example above, we would have to create an individual function for each and every property. Not too efficient!
Read More »
ECMAScript 6,
JavaScript,
React,
web developmentIn previous posts we looked at how to create mobile application projects using Apache Crodova and we saw how we could use HTML5, CSS, and JavaScript to develop mobile applications on this platform. And we also walked through the submission process of your app to various app stores (Apple’s App Store and Google Play).
One component of the submission process that we didn’t really cover is the process of taking screenshots of your application. These are required to create the “preview” aspects of your app that the app store will present before a user purchases/downloads your app. Obviously there are any number of ways you can take screenshots… everything from browser extensions, to online services, to pushing the “PrtSc” button on your keyboard. But one of the things that inevitably comes up is the need to take high resolution screenshots, particularly those of the retina displays of iPhones and iPads (displays with 2x and 3x pixel densities). Taking screenshots at these resolutions will lead to some pretty large screenshots. You can see the full list here in Apple’s developer documentation. As you can see, some of the screenshots require some fairly large dimensions. At the time of this writing, the 5.5 inch iPhones require dimensions of 1242 x 2208 pixels for hi-res portrait and 2208 x 1242 pixels for hi-res landscape. The iPad pro screenshots have to be 2048 x 2732 pixels for hi-res portrait and 2732 x 2048 pixels for hi-res landscape. Those are pretty big and you may not have a way of capturing a display this large.
So what to do? Fortunately there is a way to take high pixel density screenshots using the Firefox web browser. You don’t even need an extension and you don’t need a monitor with a high DPI (dots per inch) display. Here is how you can do this…
- To start it is assumed that you have your app viewable as a demo in the
- Open Firefox and from the menu select Tools > Web Developer > Responsive Design View.
- Set the resolution according to what you need. e.g. for 4.7-inch Retina displays (iPhone 6) set 750×1334, and for 5.5-inch Retina displays (iPhone 6 Plus) set 1242×2208
- Open the hamburger menu in Firefox and set the zoom level e.g. for 4.7-inch Retina displays (iPhone 6) you can set the zoom to 200% and for 5.5-inch Retina displays (iPhone 6 Plus) you can set the zoom to 300%. Firefox will change the pixel ratio according to the zoom level and will respond to resolution media queries. This will give you the correct responsive layout and high DPI rendering.
- Press Shift + F2 to open the console and type in “screenshot” (and maybe hit space bar) then <ENTER>. This part is important. You must use the console instead of the screenshot button to get a high DPI screenshot. Using the little screencap button in the developer tools is no good. If all goes well, you should see some kind of indication on the screen that the screenshot has been saved/created
Now you will have a high resolution screencap with the correct dimensions that you can upload into iTunes connect! Thanks Mozilla!
Apache Cordova,
CSS,
JavaScript,
mobile,
web developmentPosted by Ian on April 6, 2016 in
CSS,
HTML5For quite some time now, web developers have been making use of web fonts quite ubiquitously to add an intricate level of design to websites. Believe it or not, there was a time (late 90s / early 2000s) when there were only a handful of “web safe” fonts that developers could use and know that they’d be rendered consistently in all browsers across all systems. The main problem always has been that if the system did not have the font specified in CSS installed then the browser will usually fallback to some default font like “Times New Roman” (Ewww!) or something else. The only way to get web fonts rendering across all browsers on all systems is to have some way of downloading/importing the font into the web page that the user was viewing.
There were earlier attempts to solve this using things like cufon (*cringe*) but eventually browsers came around and all started supporting the loading of web fonts in CSS. With this approach you could include font files and reference them in your CSS like so…
@font-face {
font-family: 'Rokkitt';
src: url('fonts/Rokkitt-webfont.eot');
src: url('fonts/Rokkitt-webfont.eot?#iefix') format('embedded-opentype'),
url('fonts/Rokkitt-webfont.woff') format('woff'),
url('fonts/Rokkitt-webfont.ttf') format('truetype'),
url('fonts/Rokkitt-webfont.svg') format('svg');
font-weight: normal;
font-style: normal;
}
This approach was taken from the “bulletproof @font-face” syntax detailed by Paul Irish from Google in the article here. At the time it was written it was necessary to use all those different font formats because different browsers supported different font formats in implementing web font functionality. By putting something like the above in CSS a developer would be able to use the “Rokkitt” web font simply by specifying the font-family…
h1, h2, h3, h4, h5, h6 {
font-family: "Rokkitt"
}
As long as the paths to the font files were set properly in the @font-face block all the headers would be rendered in a slick web font called “Rokkitt.” And the great thing about web fonts is that they are not just limited to typefaces. You could also load up an icon font in the exact same manner to easily implement a vast catalog of icons into your project. Using something like Font Awesome, which was/is used by the very popular Bootstrap front-end framework developers can do something like this…
@font-face {
font-family: 'FontAwesome';
src: url('../fonts/fontawesome-webfont.eot');
src: url('../fonts/fontawesome-webfont.eot?#iefix') format('embedded-opentype'),
url('../fonts/fontawesome-webfont.woff2') format('woff2'),
url('../fonts/fontawesome-webfont.woff') format('woff'),
url('../fonts/fontawesome-webfont.ttf') format('truetype'),
url('../fonts/fontawesome-webfont.svg#fontawesomeregular') format('svg');
font-weight: normal;
font-style: normal;
}
And then use icon fonts in a project like this…
.fa-glass:before {content: "\f000";}
.fa-music:before {content: "\f001";}
.fa-search:before {content: "\f002";}
.fa-envelope-o:before {content: "\f003";}
.fa-heart:before {content: "\f004";}
.fa-star:before {content: "\f005";}
.fa-star-o:before {content: "\f006";}
.fa-user:before {content: "\f007";}
.fa-film:before {content: "\f008";}
...
By assigning the content of a particular glyph of the icon font to a class you can add that class to an element like so…
<i class="fa fa-heart"></i>
and an icon will appear inside that element! Pretty slick!
Base64 Encoding Web Fonts
As great as web fonts are, their usage does add something that we have to maintain: the font files themselves. The hitch in all this is that you have to make sure that the paths to the font files are correct and in a place of the same domain so they are not susceptible to being blocked by CORS security in browsers. However, different systems might not allow the placing of files on a server or it just might be a pain to try to manage if you have many different web fonts for different implementations. Whatever the reason, if there were some way to take the actual maintenance of the physical font files out of the equation we would probably be much better off. Fortunately for us, there is a way to do this. What we can do if we don’t want to deal with putting the files on the system? Base64 encoding to the rescue! As it turns out, there is a way that we can load up these fonts without even having to deal with the font files if we encode the fonts as Base64.
@font-face {
font-family: 'Name';
src: url(data:font/opentype;charset=utf-8;base64,XXXXXX);
src: url(data:font/x-font-woff;charset=utf-8;base64,XXXXXX) format('woff'),
url(data:font/truetype;charset=utf-8;base64,XXXXXX) format('truetype');
font-weight: normal;
font-style: normal;
}
Where the XXXXXX slots indicate where you would actually paste very very long Base64 encoded string for that particular file. And if we are not concerned about supporting IE8 or 9, or older versions of Chrome or Firefox, all we need is the WOFF format because this format is supported in all modern major browsers: Microsoft Edge, Internet Explorer 11, and the latest versions of Chrome and Firefox. So really, we just need to the one Base64 string of the .woff file.
@font-face {
font-family: 'Name';
src: url(data:font/x-font-woff;charset=utf-8;base64,XXXXXX) format('woff');
font-weight: normal;
font-style: normal;
}
All you have to do is to convert a .woff file for a web font (or icon font) to a Base64 string. There are plenty of online tools that will do this for you such as this one here.
If there is one downside here, it is that this technique *will* make your CSS slightly larger but it likely all balances out in the end because you have one fewer HTTP request to make.
CSS,
web developmentAs the web development world becomes more and more asynchronous with the emergence of technology stacks like Node.js, REST APIs, and some of the features we see in ECMAScript 6 (the latest version of JavaScript), there are whole new dimensions involved with how we exchange data over the web and how we code for this. One of the challenges with asynchronous programming is that there might be some additional considerations regarding the specific time that certain parts of your code executes and/or the order in which data is coming in to your callback functions that you set up to execute when your processes are complete. If things happen when you don’t expect them or in a different order than you expect them if you’re not ready to handle this, you’re going to get some undesirable results.

What is an example of this? What if, say, I had to do something this?
for(var i=1; i < 6; i++) {
asyncFunction(function(data){
console.log('The index is ' + i);
console.log('The data is ' + data);
});
}
Here I have set up a callback that will execute when our hypothetical asynchronous process is complete, but I also want to have access to the value of the index in the callback. If I had a list of items and I wanted to do an async process on each of the items in my list, this is some information that I would want.
If were to run this we might see something like the following in our console…
The index is 5
{ data: "item2" }
The index is 5
{ data: "item1" }
The index is 5
{ data: "item3" }
The index is 5
{ data: "item5" }
The index is 5
{ data: "item4" }
Hmm, that doesn’t look right. Why is this happening? Well, it’s because as far has JavaScript is concerned the asynchronous process that we run is done executing and JavaScript moves back up to the top of the loop and continues on. Thus, the value of the index in our loop rockets to 5 before any data comes back. What’s more, the data that we are getting back is coming in at different times in no particular order.
If we wanted to do things in a particular order, this state of things might be difficult. We might end up having to do some sorting after we get our data back for each item and we really do not have any idea when we are actually done (apart from maybe keeping a count of the response we get from our async process). This is a cumbersome and non-performant way of doing things. What we need is a way to maintain the context of the index of our loop in our callback function(s) so that we are able to keep some semblance of order as we do these async processes. How can we accomplish this?
Read More »
AJAX,
web development