Fetch API, the new sexy way of making ajax requests.

One of the most cool stuff I have find in ES6 is the new Fetch API, which will replace the old XMLHttpRequest.

This is a brief overview of the feature

A simple request looks like this:


fetch(“json.json”).then(function(response) {
return response.json();
});

That fetch() method is a global method that starts the request process.

It receives two arguments:

  • The first might be a url string or a request object
  • The second one is an options array, It can contain stuff like the HTTP method (GET, POST, etc), headers, a request body, etc.

fetch() returns a promise which resolves into a Response object.

 

Request and Response interfaces

The Request interface allows you to create a request object and pass it to fetch()

The constructor receives two arguments, the same as the fetch() method.

 

The Response allows you to handle the response of the request.

 

These two interfaces implement the Body mixin

Body provides a set of methods for handling the Response/Request body.

 


This is the end of this overview, but if you want to learn more about it, please leave a comment or check this documentation:

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

Thanks for reading,

lg

A couple of resources to learn JavaScript with confidence.

This week post is about a couple of resources that I find quite interesting to take a look, being you a beginner or even intermediate developer in the JavaScript world.

How to Learn JavaScript Properly

The first of them is a free course at JavaScriptIsSexy.com

With a seven to eight week duration, divided in two paths, beginner and experienced, employs a combination of books and blog articles guides you through the basics of the language and builds until you are able of developing an application with confidence (and without too much googling).

It uses code school JavaScript path as practical exercises and later a quiz application that also works as the final project of the course.

I only took the experienced path so I don’t know exactly how the beginner one differs, but I think that the difference is the depth in which each topic is discussed.

The course can be accessed here

 

You Don’t Know Js

The second one is a series of books called You Don’t Know Js. They provide a in deep knowledge of the language, maybe not that adequate for complete beginners but extremely useful for any decided to deepen his/her knowledge of the language.

Free if read online, can be checked out here

Each of the six books such as scopes and closures, objects in js or the new features of ES6.

At the moment of writing this, I’m still reading them, beginning the fourth one, so I might add more detailed information about each one after I finish them all.

 

That would be all for today, if you find this useful, got any other cool resource to share or anything else, please feel free to leave a comment.

Thanks for reading.

lg

Starting a blog – SimpleProgrammer email blogging course

One of the reasons why I was able to start this blog was because I subscribed to a free email course by SimpleProgrammer, by John Sonmez.

This is a balance, after finishing the three weeks course.

The course ware comprises 6 short emails which take less than 5 minutes to read and at the end it has a homework related with the topic of the lesson.

It also provides a couple of discounts links for products that we might use to setup our blog, like hosting platforms, marketing courses and the email course itself in pdf format.

The main advantage I find is that it make you be constant and don’t quit after the first blog post. Since each lesson comes out on Mondays and Thursdays it can help to use those days to focus on your blog.

The homework’s also provides a way to start gaining traction and maybe start developing a habit of consistency, specially a couple of them that make you determine the scope and niche of the blog, the topics covered inside of that niche and the periodicity of the blog posting.

For example I try to post each Thursday, and even though I’m just starting I will focus on JavaScript and web development, at least for the following months.

To sum up,

I find John Sonmez SimpleProgrammer email course a great option for those of us that always wanted to have a blog and try to develop our careers further.

I am convinced that the hard and technical skills alone are not enough to advance as professionals, writing a blog, I think, help to improve other aspects of our skill sets, such as the ability to express ideas, as well as forces us to deepen our knowledge of a topic to be able to write about it.

Thanks for reading,

lg

Using Require.js

I am working on a quiz app to improve my knowledge of javascript and when I started to use Backbone I started to see how my dependency list began to grow, because its forces you to have a more modular approach.

The solution to this is was using require.js, which is a module loader, it handles all the dependency management for you, more or less.

So I think it’s a good idea to share with you a small guide to get require.js up and running.

This is its site, if you want to check it: http://requirejs.org/

Also, you can donwload it from here:

http://requirejs.org/docs/download.html

There is another importan plugin that we will be using, requirejs/text, just text from now on

Text allow us to easily load html files, json files, etc.

It can be downloaded here:

https://raw.githubusercontent.com/requirejs/text/latest/text.js

Or follow the instructions on its github repo:

https://github.com/requirejs/text

Setting up:

I wont tell you where to place the files… just make sure that you place require.js in the root of your js folder.

So, first we will work on the index.html file.

If you are loading any script or file that could be loaded by require, remove it from your index. And add the following line:


<script data-main="path/to/main/file" src="path/to/require.js</script>

In the scr attribute you set your require.js path.

In data-main you set the path to the main file of the application, call it main.js, app.js, index.js, etc. I will call it app.js from now on.

In app.js you need to add a couple of things.

The first is setting up the require config. Here you declare custom paths to modules, define base directories, etc.

This only needs to be defined once, or event none if you dont need to set custom paths.

After that, you do the actual module loading, this can be done with two functions, require(or requirejs witch is the same) and define.

require is used when you load a module once.

define is used when you will reuse a module.

Both are similar in the way you pass them parameters:

Assume that we have three modules, a, b and c, it would be something like this.


function([“path/to/a”,”path/to/c”,”path/to/c”], function(a,b,c) {

//module code

});

I will show you some code examples, to make this clear.

First this is the app.js file from my quiz app.

requirejs.config({
paths: {
templates: '../resources/templates',
jquery: 'libs/jquery',
backbone: 'libs/backbone',
underscore: 'libs/underscore',
text: 'libs/text',
bootstrap: 'libs/bootstrap'
}
});

requirejs(['jquery','views/quizView','views/userView','models/quizModel','models/userModel','views/summaryView'], function($, QuizView, UserView, Quiz, User, SummaryView) {
$(document).ready(function() {

if (sessionStorage.getItem("currentUser")) {

var quizView = new QuizView({model: new Quiz()});

} else {

var userView = new UserView();

}

});

});

As you can see, in requirejs.config I setup the paths to my dependencies, and to my templates folder, this would be use later as a base path for my templates.

After that is called the requirejs function. Can you see how in the case of jquery the path defined above is used?

Also, the modules inside the function passed as second parameter to requirejs must have the same order as those in the array.

Also, to show you how the text plugin and define works, here is another module, userView:


define(['underscore', 'backbone', 'views/quizView', 'models/userModel', 'models/quizModel','text!templates/login.html'], function(_, Backbone, QuizView, User, Quiz, loginTemplate) {

var UserView = Backbone.View.extend({

//view code

});

return UserView;

});

I chopped off the module code because it is out of the scope of this post. I just leave the return statement, so you can see how it returns the module.

Look at ‘text!templates/login.html’

Here is how the text plugin is used, adding text! at the beginning of the the module path.

Also, templates, is the path defined above, in requirejs.config

I hope you find this tutorial useful.

Please if you have anything to add or any questions feel free to leave a comment!

Thanks for reading,

lg

Building a Javascript web application from scratch

Hello, welcome to my blog! This is the first of many posts, hopefully. I don’t really know how to start a thing like this, so I’ll go straight to the point.

In the last month have been following an awesome JavaScript course from javascriptissexy.com. Although I know JavaScript, I wanted to learn it better and feel more confident when coding.

The end result is a quiz, very basic, yes, but covers all the aspects you could see in a major web application, so in this first series of posts, I will show what I have build, and the thoughts and ideas that popped along the way.

GitHub:

You can find all the code in this repository

I thought that separate the different versions in folders would make it easier to check one or another.

Setting up:

The requirements for this project were simple, build a quiz where an user can answer questions and get a result at the end, mine is about a Song of Ice and Fire, because is awesome.

There was no requirement about using a framework, so I decided that for the first iteration I would use plain js. I want to see how much could I do without needing to use jQuery(or any other framework) to be more productive.

The files architecture is simple, just an html file and a js one. The project is small.

Screenshot from 2015-12-21 07:58:15

As a note, I am using brackets as my editor.

Starting to code:

First of all, this is my index.html:

<!DOCTYPE html>
<html>
<head>
<script src="js/app.js"></script>
</head>
<body>
<div id="container">
<form id="questionForm">
<div id="title"></div>
<div id="questions-box"></div>
<div id="btn-next-container">
<input type="button" value="Next!" id="btn-next">
</div>
</form>
</div>
</body>
</html>


As a html pages loads asynchronously one of the things that have to been taken in account is that some of the js code may load before the html code it is supposed to work with.

 

For this, we need to wait until the page is loaded. In plain js there are a couple of ways of doing this, I decided for the following:


document.addEventListener('DOMContentLoaded', function() {
 …
 }

The DOMContentLoaded event is fired when all the html is downloaded, so it will prevent any possible issues.

There is another way of doing this, and it is using the load event. The main difference is that DOMContentLoaded does not wait for stylesheets, images and other resources to be load.

This is the full code of the event listener:


document.addEventListener('DOMContentLoaded', function() {

var title = document.getElementById('title');
 title.appendChild(document.createTextNode(quiz.title));

getNextQuestion();

var btnNext = this.getElementById('btn-next');
 btnNext.addEventListener('click', handleClick);

})

 

 

Nothing fancy here. I setup events handlers and call getNextQuestion() which is the method that do the magic.


function getNextQuestion() {

var questionsBox = document.getElementById('questions-box');

questionsBox.innerHTML = "";

quiz.currentQuestion += 1;

if (quiz.currentQuestion < quiz.questions.length) {

var btnNext = document.getElementById('btn-next');
 renderQuestion(questionsBox, quiz.questions[quiz.currentQuestion]);
 btnNext.disabled = true;

} else {
 showSummaryScreen();
 }

}

Can you see that quiz variable? That is the js object that stores all the quiz data, let me show it to you:

 var quiz = {};

quiz.questions = [
 {
 question: "The Westerosi capital population is:",
 answers: [
 "half a millon",
 "a quarter of a millon",
 "seven hundred thousands"
 ],
 solution: 0
 },
 {
 question: "The number of The Free Cities is:",
 answers: [
 "seven",
 "eigth",
 "nine"
 ],
 solution: 2
 },
 {
 question: "The heigth of the wall is:",
 answers: [
 "a thousand feets",
 "seven hundred feets",
 "three hundred feets"
 ],
 solution: 1
 }];

quiz.title = "A world of ice and fire numbers";

quiz.currentQuestion = -1;
 quiz.correctAnswers = 0;

It structure is simple, quiz.questions stores each question with its texts, answers array and solution.

There are other two attributes to note, currentQuestion and correctAnswers.

currentQuestion contains the index of the current question, it works as a counter, so after the user submits the last one I can show the summary screen with the results.

correctAnswers just sums one for each correct answer the user make.

So, getNextQuestion calls two methods, while there are questions left, it calls renderQuestion(), which just create the html for the next question to be shown.


function renderQuestion(questionDiv,questionData) {
 var questionTitle = document.createElement('h2');
 questionTitle.appendChild(document.createTextNode(questionData.question));

questionDiv.appendChild(questionTitle);

for (i = 0; i < questionData.answers.length; i++) {

var answer = questionData.answers[i];

var answerBox = document.createElement('div');

var radio = document.createElement('input');
 radio.setAttribute('type','radio');
 radio.setAttribute('name','answer');
 radio.setAttribute('value',i);

radio.addEventListener('click', function clickEventListenerHandler() {

var btnNext = document.getElementById('btn-next');
 btnNext.disabled = false;

this.removeEventListener('click', clickEventListenerHandler);
 })

var answerText = document.createElement('p');
 answerText.appendChild(document.createTextNode(answer));

answerBox.appendChild(radio);
 answerBox.appendChild(answerText);

questionDiv.appendChild(answerBox);

}
 }

The other one is showSummaryScreen(), but first, I think we should take a look at handleClick()

This function was attached to the click event of the btn-next at the DOMContentLoaded event listener.


function handleClick() {
 var form = document.forms[0];
 var checkedAnswer;

for (i = 0; i < form.elements.answer.length; i++) {
 var answer = form.elements.answer[i];

if (answer.checked === true) {
 if (checkAnswer(answer.value, quiz.currentQuestion)) {
 quiz.correctAnswers += 1;
 }
 getNextQuestion();
 break;
 }
 }
 }

In case that there is a selected value (which should, since the button is disabled otherwise), it calls checkAnswer() and gets the next question.


function checkAnswer(answer, qindex) {

var question = quiz.questions[qindex];

if (answer == question.solution) {
 return true;
 }

return false;
 }

checkAnswer() just compares the answer id with the currentQuestion solution. If they match, we got a winner.

The last method is showSummaryScreen(), it does what it says:


function showSummaryScreen() {
 var container = document.querySelector('#container');

container.innerHTML = "";

var result = quiz.correctAnswers / quiz.questions.length;

var summaryTitle;

if (result == 1) {
 summaryTitle = document.createTextNode("Congratulations! Your knowlledge of the world put most of the schollars and maesters to shame!");
 } else if (result > 0.75) {
 summaryTitle = document.createTextNode("Excelent! You got "+quiz.correctAnswers+" out of "+quiz.questions.length+" questions. You should visit the citadel, if you have not do so, to improve even more!");
 } else if (result > 0.5) {
 summaryTitle = document.createTextNode("Well enougth! you got "+quiz.correctAnswers+" out of "+quiz.questions.length+" questions. A maester would do better, but for a chainless man this result is good");
 } else {
 summaryTitle = document.createTextNode("Clearly you do better with a sword than with numbers and facts! You got "+quiz.correctAnswers+" out of "+quiz.questions.length+" questions.");
 }

container.appendChild(summaryTitle);

}

The messages are not the best but I promise to improve them someday!

Conclutions:

Ok, now that I have presented the code I would like to share with you a couple of thoughts.

The first is that plain js is very powerful, at least more that what I belive it to be. In the past I would do all this with jQuery, but take for example document.querySelector, I dont think that most developers know about this, and it is essentialy the same as doing a $(“”)

The second one is that there are still things that are quite painfull, for example the way of loading a local json file, it inolves something like this:

 function loadJSON(callback) {

var xobj = new XMLHttpRequest();
 xobj.overrideMimeType("application/json");
 xobj.open('GET', 'path/to/json', true);
 xobj.onreadystatechange = function () {
 if (xobj.readyState == 4 && xobj.status == "200") {
 //your stuff
 }
 };
 xobj.send(null);
 }

And with jquery we can simplify it to something like this:


$.getJSON("path/to/json", function() {
 //your stuff
 });

For this and other reasons I had to made v2. I will write and upload its post in the following days. So please, if you like this, or see something that is not write and can be improved, comment.

Thanks a lot!

lg