Tip of the week – run html pages from Github

Did you know you could easily run an HTML page from Github?

The solution is rawgithub !

Just go to the file you would like to run and click on raw button. This will show the page but served as text/plain and not text/html.

So that you run the file as text/html on the url just delete the dot from rawgithub.

Before:

https://raw.github.com/nmoliveira/requirejs-demo/master/blog.html

After:

https://rawgithub.com/nmoliveira/requirejs-demo/master/blog.html

Very nice to share code or show some demos, but, beware, this is not for production! This is not an alternative to hosting services!

Check Can I use rawgithub.com on a production website?

Advertisements

Get into RequireJS

Intro

Hi all, welcome to Get Into RequireJS! If you have good skills on javascript and already knows about the Revealing Module Pattern, get ready because, I will go cut to the chase!

What is RequireJS?

RequireJS is a module loader. Its functionality is to load modules and take care of dependencies for you. When you define a module, you will identify its dependencies and RequireJS will load those dependencies in runtime and just when they are needed!

How to add RequireJS to the project?

RequireJs assumes that you have a specifc directory structure in your project. Of course you can override this settings, but for the demonstration I will follow the default structure, which is the following:

project-directory/

  • project.html
  • scripts/

Under the scripts folder, you will have all the javascript for your project. I always suggest to have the third party libraries separated from your files, so, in my demo I have the following structure:

project-directory/

  • blog.html
  • scripts/
    • app/
    • lib/
    • main.js

Where my code goes to app folder and third party goes to the lib folder.

In the html page you will just include the RequireJS:


<script data-main="scripts/main" src="scripts/lib/require.js"></script>

The data-main attribute, indicates to RequireJS, that once it is loaded, it will have to load the scripts/main.js file. There are other ways to do this, but this one, without any configuration, is definitely the simplest one. Note that I did not refer main.js but only main, this is because RequireJS expects to load only javascript files, so you can omit the extension when you refer your modules.

On the main.js, normally I have some RequireJS configuration and the first call to my application API:


// requirejs configuration

// Define baseUrl (the base folder for the js files)

// Define path to jQuery

requirejs.config({

  baseUrl: 'scripts',

  paths: {

    jquery: 'lib/jquery'

  }

});

// Start the main app logic.

requirejs(['app/blog'],

  function (blog) {

    blog.start();

  });

In the code to start the application, I am saying to RequireJS that I need the module blog and then I can call my function that starts the application. We will just see how that works.

How to define a module?

The structure of a RequireJs module, follows the Module Pattern

In my demo I have the following module (file app/blog.js):


define(['app/dataservice', 'app/presenter'], function(dataservice, presenter){

  var start = function(){

    dataservice.getPosts(presenter.renderPosts);

  };

  return {

    start: start

  }

})

The code indicates that the module blog, depends on dataservice and presenter modules. On the start function, I am calling getPosts on dataservice module and I am passing the renderPosts on the presenter module as callback (not the best way, but for demo purpose is fine).

Picking one of the dependencies modules, for instance the dataservice, it is very similar as it also follows the same structure:


define(['jquery'],function($){

  var getPosts = function(callback){

  $.get('data/posts.json',callback)

  };

  return {

    getPosts: getPosts

  }

})

Final notes

There are a lot of configuration that you can do, different ways to load modules but, this was a cut to the chase, just to show how easy is to use RequireJS. If you thought it was interesting and want to start using it, I suggest to take a look at the documentation first.

You can download my complete demo in Github.

preview

Ajax requests on jsFiddle

Did you know that you could create XHR requests on jsFiddle? If you didn’t know,  just keep reading..

To improve user experience jsFiddle has created the echo features. One of its features is to provide to developers the possibility to create XHR requests. It is very simple to use:


  &amp;lt;div class='wrapper'&amp;gt;
  &amp;lt;p&amp;gt;JSON will be received in 3 seconds&amp;lt;/p&amp;gt;
  &amp;lt;div id='post'&amp;gt;&amp;lt;/div&amp;gt;
  &amp;lt;/div&amp;gt;

This is my HTML, a simple div with id=post will be appended with the response from the request.

To make a request, I have used jQuery and it looks like this:


// My request

$.ajax({
  type: &amp;quot;POST&amp;quot;,
  url: '/echo/json/',
  dataType: &amp;quot;json&amp;quot;,
  data:{
    json: JSON.stringify({
      text: 'Response from server',
    }),
    delay: 3
  },
  }).done(function(response) {
    show_response(response);
});

// append data from response to my div
show_response = function(obj, result) {
    $('#post').append(obj.text);
};

My request is just a simple jQuery ajax() call. There are some things that we have to provide.

The data has to be a POST call.  The url points to   ‘/echo/json/’ because I’ve chosen json to represent my data, but there is other types available (including XML).  The ‘json’ object that you define on the request, will be the object that you’ll get on the response. The optional ‘delay’ parameter, it’s a time in seconds after which data should be returned.

And this is pretty much it! Simple and very useful if you, like me, use jsFiddle to share code samples, help anyone or just quick testings!

You can see the live example here.

Javascript pre-compiled templates with Handlebars.js

Handlebars is a template engine based on mustache.  The code blocks are delimited by {{ .. }}

Here’s an example of a Handlebars.js template:

<script id="todos-template" type="text/x-handlebars-template">
  {{#each todos}}
    <div class='todo-item'>
    <p>Title: {{ this.title }} </p>
    </div>
  {{/each}}
</script>

Rendering a template is a two stage process: Compile and Execute.

1 – To compile we should do this:


var source = $("#todos-template").html();
var template = Handlebars.compile(source);

2 – To execute we do this:


var context = {
  todos:[
    {title: "Task 1"},
    {title: "Task 2"}
  ]
}

var html = template(context);

See live demo

The process of compiling the template is in fact, converting the template from string, to javascript function, that we call later with our data. The compilation is the most expensive in terms of performance. So if you want performance, make sure you compile each template once and, cache the template functions and, reuse whenever you need.

So, now is where things get interesting. One of the most important features of Handlebars.js, is the support for pre-compiled templates. Pre-compiled templates, as the name states, are templates previously compiled instead being compiled in run time.

So this means, that we can get rid of the most expansive part of the template process!

Handlebars includes support for pre-compiling file-based templates. It is possible to have a script that finds all your templates (in separated files), compiles them and put them in one single file!

To achieve the compilation as a build step, we need to have installed node.js and npm.

After installing both, we need to install also the Handlebars npm package like this:

$ npm install handlebars -g

The -g flag installs the package globally, so it can be used in any project.

And now, we are ready to start using the precompiler. On the console you can do:


$ handlebars <input> -f <output>

The compiler will insert templates in Handlebars.templates. If, for example, you had an input file todos.handlebars, the compiler would insert it at Handlebars.templates.todos.
In my previous example and having a folder called “templates” with all my Handlebars.js templates, I would compile them like this:


$ handlebars templates/ -f templates.js

Handlebars then, would create a single file with the combined templates under templates folder in a templates.js file that we need to include in our page.

Back to my example, now, instead of having:


var source = $("#todos-template").html();
var template = Handlebars.compile(source);

I can have just:

var template =  Handlebars.templates.todos;

The main idea to retain is that skipping the compilation at run time, we are avoiding the most expensive step of template rendering in terms of performance!

Check on my github the code for a simple example using precompiled Handlebar.js templates and Backbone.js

List of references:
http://handlebarsjs.com/

Javascript Revealing Module Pattern

On a previous post  I refer the javascript Revealing Module Pattern, in this post I want to explain how it works and how can it help you to structure your javascript code. 

First lets look to its structure:

var Calculator = function() {
  // code goes here
}();

The code starts with a definition of a variable, which we associate a function that is invoked as soon as as the script loads (this is done with the “()” at the end).

Your variables and functions should go inside of the Calculator in the “code goes here” part.

Now, one of the most interesting parts, inside the Calculator we can declare private and public members. For the private members we just have to declare them inside of the Calculator and, for the public members, we have to add a return statement and declare the public members inside it.

Lets look at the structure of the complete Revealing Module Pattern:

var calculator = function() {
  // private members goes here
  // ...
  // public members goes here
  return{
    // ...
  };
}();

And now lets look at the implementation of the Calculator that just adds and subtracts 2 numbers and logs the result to the console if configured that way:

var Calculator = function() {
  // private members goes here
  var privateLog = false;
  var privateConfig = function(shouldLog) {
    privateLog = shouldLog;
  };
  var privateAdd = function (x,y) {
    var result = x + y;
    if (privateLog) {
      console.log(result);
    }
    return result;
  };
  var privateSubtract = function (x,y) {
    var result = x - y;
    if (privateLog) {
      console.log(result);
    }
    return result;
  };
  // public members goes here
  return{
    publicConfig: privateConfig,
    publicAdd: privateAdd,
    publicSubtract: privateSubtract
  };
}();

Calculator.publicConfig(true); // configures Calculator to log to console
Calculator.publicAdd(1,2); // logs 3
Calculator.publicSubtract(2,1); // logs 1

Analyzing the code for the Calculator, you can see that all public members are exposed in the object literal that is returned when the Calculator is invoked. All the other members are private and cannot be accessed outside of the Calculator.

The Revealing Module Pattern is one of my favorites design patterns to structure my javascript code because it is easy to implement, easy to read (which is good for maintenance) and for the capability to declare private and public members.

You can see this code in this jsFiddle.

Get into Breeze.js

Last week I’ve started to play with Breeze.js and it really seems to be a great tool for developing reach client side applications.

In this post I wanted to let you know about some of its core features and, perhaps, make you curious about it.

I’ve also made available a quick sample project if you want to see Breeze.js in action.

So, what is Breeze.js? 

Breeze.js is a JavaScript library that manages data in rich client applications.

How does it work?

Breeze creates dynamic objects,  that mirror your server-side objects. The properties of these objects can be bind to the controls on the UI and any change made on the data model, will be tracked and updated on the UI automatically.

What can I do with it?

There  are several quite interesting and useful features that Breeze.js provides:

  • Rich Queries with Linq-style syntax
  • Change tracking
  • Validation
  • Support for Entity Framework, Odata and Web API
  • Support for NoSQL, non-.Net and SOA back-ends
  • Data management
  • Batched saves
  • Support for various JavaScript Libraries like Knockout, Angular and Backbone

Rich Queries

Example of a simple query with filter and order:


var query = breeze.EntityQuery.from('Cities')
 .where('CountryName', '==', 'Portugal')
 .orderBy('CityName');

Remember, it’s JavaScript! Nice, right?

Track changes and do batched saves

With Breeze.js we can make every CRUD operation with its objects and save everything in a bulk operation.

Below a quick snippet:


// save all changes in one operation

manager.saveChanges()
 .then(function () { alert("changes saved"); })
 .fail(function () { alert("error saving"); });

The manager is a Breeze.js EntityManager and it is the service gateway and cache holder.

Quick sample

I’ve made a simple project where you can check Breeze.js in action.

It’s a small page that lists some world cities and you have a search form to filter the records.

The project was developed with ASP.Net MVC, EF Code First, Knockout and of course Breeze.js

https://github.com/nmoliveira/GetIntoBreezeJS

preview

References:

http://www.breezejs.com/documentation/introduction