Minification using Grunt/Uglify

Assuming you have npm installed, run the following commands in the terminal. Navigate to the project where you want to use Grunt.

$ npm install -g grunt-cli
$ pwd // im in /usr/home/myname/workspace
$ mkdir test-grunt // our test grunt project directory
$ cd test-grunt
$ npm init // it will ask some questions to create a package.json file in this directory

add a directory called scripts/src and put some js file in it, one or more

create a file called Gruntfile.js in the directory where your package.json resides

copy-paste the following code in your Gruntfile.js

module.exports = function(grunt){

  grunt.initConfig({

    pkg : grunt.file.readJSON('package.json'),

    // tasks here
    uglify : {
      compress : {

       // file array format.. also see compact format in the resource given below
       files : [
        {
          // flag to indicate grunt to expand the options given below it
          expand : true,
          // path relative to which the regex in src will be matched
          cwd : 'scripts/src',
          // array of paths relative to cwd, specified above
          src   : ['*.js'],
          // will create a dest directory inside scripts and place the min files there
          dest : 'scripts/dest/',
          // extension of the minified files.. you could have something like .prod.js, for production versions
          ext : '.min.js'
        }
       ],

        options : {
          // really helpful during development, to see how less useful optimizing the uncompressed file actually is !
          // shows the size of original js files, minified and also gzipped files
          report : 'gzip',
          // to help optimize the varibale names and stuff like that
          compress : true
        }
      }

    }

  });

  grunt.loadNpmTasks('grunt-contrib-uglify');

  grunt.registerTask('default', ['uglify']);

};

run the following command to tell grunt that you task is dependent on a plugin called uglify..

npm install grunt-contrib-uglify --save-dev

this option will help add the dependecy parameter in the package.json file. Checkout package.json after you run this commnd and you will see the dependency added, along with compatible version number.

now run the following:

$ grunt // will show a verbose result and finally a report indicating the sizes of original, minified and gzipped versions as requested.

In the next post, I’ll write how to make use of this minified file and setup apache to compress it.

Resources :

Getting Started with Grunt and the Further Reading section of it
UglifyJS plugin for Grunt

Posted By

Using Backbone Stickit with RequireJS

In pursuit of finding a validation plugin for Backbone, found this very useful thing for two-way binding in Backbone, called Stickit, which helps bind views(especially form elements) to model attributes and the other way round. Struggled to get started with it, as the guys who created it sadly don’t show its usage in AMD format. And adding to the sadness and struggle, not much help from Google too ! With some trial and error keywords, found this and that is what I’m gonna re-write here, just that I’ll “stick” to the point.

So here’s my main.js file with the require config :


// main.js
require.config({

  paths: {
    underscore : 'lib/underscore-min',
    backbone   : 'lib/backbone-min',
    backbone_validation : 'lib/backbone-validation-min',
    backbone_stickit       : 'lib/backbone-stickit-min',
    text : 'lib/text'
  },

  shim : {

  	underscore : {
  		exports : '_'
  	},

  	backbone : {
  		exports : 'Backbone'
  	},

  	backbone_validation : {
  		deps : ['backbone'],
  		exports : 'Backbone.Validation'
  	},

  	backbone_stickit	  : {
  		deps : ['backbone']
  	}

  }

});

require(['app'], function(app) {
  // use app here
  app.init();

});

// view file..
define(
	[
		'underscore',
		'backbone',
		'backbone_stickit',
		'text!templates/test/tmpl_test.html'
	],

	function(_, BB, stickit, tmplTest){

		var TestView = BB.View.extend({

			el : '.content-container',

			initialize : function(){

				this.render();
			},

			bindings : {
                                // element selector in the form mapped to model attribute
				'#test-name' : 'name'
			},

			render : function(){
				var html_test = _.template(tmplTest, {});

				this.$el.html(html_test);

				this.stickit();
			}

		});

		return TestView;

	}
)

So that’s it, to get started. More resources below ..

Backbone Validation Plugin

JS 10: Everyday is a RnD Part II – Modular Backbone using AMD format

Stickit Annotated Source

Stickit Github Repo


Posted By

Backbone Bits #1

I recently faced a problem of circular dependency while working on Backbone and RequireJS. Here I write the problem and the solution that worked for me.

Problem : I had two models, which depended on each other, but as this doc says, if model-1 depends on model-2 and vice versa, calling module-2 gives module-1 as undefined and this is what happened with me. But one of my models just required the other and not depended on the other. What I mean is, model-b could be created , without model-a, it just needed model-a in some function. So it was actually my mistake to have defined dependency badly.

Here’s the initial code :

// model_a.js
define(['backbone','model_b'], function(backbone, modelB){

});

// model_b.js
define(['backbone','model_a'], function(backbone, modelA){
    
});

Solution : may seem simple but I had hard time figuring this out.

My model-a needed model-b in the initialize function, so it actually depended on model-b, where as model-b just needed model-a in some change function.

So this worked :


// model_a.js
define(['backbone', 'models/model_b'], function(backbone, modelB){

// model-a code

});

// model_b.js
define(['require','backbone'], function(require, backbone){ 
    var modelA = require('models/model_a');
    
    // here i can use modelA without problems
});

Posted By

Handling DB errors in Codeigniter

I was developing a login system for a sample app and had to deal with “account already exists” error by checking if the email provided already existed in DB. Though it could be done by running a select count(*) where email = ‘email_provided’ query, this could possibly not be the best way. So googling gave me two methods that could be of use $this->db->_error_message() and $this->db->_error_number(). But had no results using this. The ajax call was just failing repeatedly !

So here are the code snippets..

// $query and $params passed from another function

$response = $this->db->query($query, $params);

if(!empty($this->db->_error_message())){

// error handling here. didn't work

}

The above code threw an error saying “Fatal error: Can’t use method return value in write context in C:\projects\baccount\application\core\MY_Model.php on line 19″. The problem here is actually a limitation of empty function, which takes a variable and not a return value. So changed this to :

$error = $this->db->_error_message();

if(!empty($error)){

// error handling here.. this works

}

Running the user account creation query, with a duplicate email, it failed again saying “Error number 1062 : Duplication entry for email = email_provided”.  To enable custom error handling, you need to disable the automatic handling by turning $db['default']['db_debug'] to FALSE. And the code works as intended.

Posted By

php Bits #1

While working on Codeigniter today,I came up with a need to extend Session class of the framework. So wrote a class called MY_session, in application/libraries , which extended the Session class. As given in the user guide, while loading the session library, I just needed to write $this->load->library(‘session’) and it would automatically load the extended class. This worked fine , while working on localhost, but failed to work soon as I uploaded it on the test server. So perused the user guide to see if there were some things to be taken care of. And finally noticed one little thing: in all the examples given, they had class names starting with uppercase letter. Though MY_session starts with uppercase, I guess that wasn’t good enough. It had to be MY_Session, and this change made it work on the server. So how and why the hell it did work on my local system ?! I truly donno. But my friend guessed, the only difference was, I worked on a Windows system and the server was a Linux machine.. So that could be the reason !

Resource : 
Creating Libraries : Codeigniter User Guide – Awesome Guide :)

Posted By

Module and Revealing Module in JS

While starting with Javascript it’s often the case that our js file looks like a list of variables and functions dispersed throughout the file. consider a variable “a” , on which two operations can happen “increment” and “decrement”. Now how did I code this spec six months back ? Like this :

var a = 0;

function inc(){
   a++;
   console.log(a);
}

function dec(){
   a--;
   console.log(a);
}

How did I code this about five months and three weeks back ? Like this :

var a   = 0,
    inc = function(){
       console.log(++a);
    },
    dec = function(){
       console.log(--a);
    };

But as the specs list grows there will be many such vars.. and consider there’s one more variable b , with almost the same operations on it.. or a bit more.Then we can’t define just a variable and name the operations again as inc and dec, because in global namespace they are already taken. So it’s better to write it modular.

var obj = {
       a : 0,
       inc : function(){
         console.log(++this.a);
       },
       dec : function(){
         console.log(--this.b);
       }
    };

But the problem with this is a can be modified directly as obj.a = 10, for example. Javascript doesn’t have access specifiers like “private” and “public”, but can be implemented with the help of closures like this :

var obj = (function(){
       var a = 0;

       return {
          inc : function(){
              console.log(++a);
          },
          dec : function(){
              console.log(--a);
          }
       }
    })();

This is a self-executing anonymous function which returns an object, that exposes the operations to be performed on a, and that’s the only way it can be edited now, i.e obj.a would now be undefined. This is
the JS way of making variables “private”. And this is called the Module Pattern. The problem with this is , each time you need to access one public property inside another , it should be done with the >em>this or via the main object name. What I’m saying is :

var obj = (function(){
       var a = 0;

       return {
          inc : function(){
            return ++a;
          },
          // accessing inc inside incAndShow requires use of this every time
          incAndShow : function(){
              console.log(this.inc()); 
          }
       }
    })();

So Christian Heilmann created a Revealing Module pattern, that involves declaring and defining every property as a local variable sharing them as necessary. The above code in revealing module pattern would be :

var obj = (function(){
       var a   = 0,
           inc = function(){
              ++a; // no this here !
           },
           incAndShow = function(){
              console.log(inc()); // no this here too !
           };

       return {
          // no function definitions here.. this looks pretty , brief and neat !
          inc : inc,
          incAndShow : incAndShow
       }
    })();

So that was module and revealing module from me . Hope to come up with more patterns..

Resources :
Design Patterns – Addy Osmani
Module Pattern – Javascript Playground
IIFE – Ben Alman

Posted By

js Bits #3 – Bubbling and Capturing

Today one of my friends was asking me about event handling and the phases of it and why the phases matter. So here is my post on why it matters. Starting with history, Netscape introduced the capturing phase and MS introduced the bubbling phase , and W3C rightly said let’s have both and give developer the option to select when he wants to handle an event. Most of the browsers now support both(except IE, as far as I know). So consider a scenario, when click event anywhere on body element has some common functionality such as if a popup box is open anywhere in the page it should be closed. So its as simple as this :

document.getElementsByTagName("body")[0].addEventListener("click",function(e){
   // hide the popup here
}, false);

Now that would mean if you click on the popup itself , it will be hidden too ! And that’s not usually expected. But why the hell is click triggered on body when you have clicked on popup ?? because it’s a descendant of body. To make it behave as expected, we could either check for the e.target inside the body click handler and execute accordingly or we can write a popup click handler and stop propagation there. Writing exceptions in body click handler will be logically illogical if number of such exceptions rise. What we can do is write separate event handlers for such exceptions and stop the propagation of event so that it doesn’t reach body. But in capturing phase body gets notified of the event before the popup itself, that is, if the the third option in the above code snippet was true, no matter how many event handlers you have for specific situations , body click handler will be executed before them. So make it false indicating that it should be executed in bubbling phase and you can handle the propagation of events.

Resources :
Quirksmode- awesome for studying events
Events Order – QuirksMode
Uses of Capturing an Bubbling – StackOverflow
Working of Event Propagation – StackOverflow

Posted By

Backbone – Login Form II (Validations)

Had an introductory post on Backbone here. And this one is slightly enhanced.

First here is the screenshot of the login form :

Backbone Login Form

and this is where you can find it in github.

 

Other tools Used
Bootstrap
Less CSS

Will be happy to get feedback :)

Posted By

CSS Bits #1

Came through this article last night and was wowed by one particular trick, that is to make head and elements inside it visible. Though many might say that it’s just like any other tag or something like that, seriously I had never thought of this. So to make head element and others inside it visible you just need to do this :

head{
  display : block;
}

style, link, script{
  display : block;
  /* to make it readable.. test removing this */
  white-space : pre;
  /* to make it appear like raw code and not text */
  font-family : monospace ; 
}

So that was my post on CSS..

Posted By

Macros in Sublime

This post explains adding keyboard shortcuts for macros in Sublime Text 2. So here it is ..

1. Start recording a macro.. Go to Tools -> Record Macro
(shortcut : Ctrl+Q)

2. Type the keystrokes you want to record and hit Ctrl+Q again to stop recording. Now hit Ctrl+Shift+Q to playback the recorded macro.

3. Go to Tools -> Save Macro.. Sublime asks for the filename and the location of the file is usually C:\Users\<Your Username>\AppData\Roaming\Sublime Text 2\Packages\User .. Give it some meaningful name and done, the macro is saved.

4. Now go to Preferences -> Key Bindings – User . It probably will be an empty array.

Paste the following code inside it :

// single quote string .. to remember what it does
{
   "keys": ["ctrl+alt+q"],
   "command": "run_macro_file",
   "args": {"file": "Packages/User/single-quote.sublime-macro"}
}

Replace the ["ctrl+alt+q"] with the set of keys you want to . and the value of args should be the location of the macro file.

Then try pressing the key bindings you have just added and Whoa !! it plays back the newly added macro.

Resources :

Banish Repetitive Tasks with Sublime Macros – Webdesign Tutsplus

Posted By