Pair program with me! profile for carousel at Stack Overflow, Q&A for professional and enthusiast programmers

12/16/2013

Dissecting Laravel Application class



This class along with core framework represents cornerstone of internal Laravel machinery. In the spirit of good software design it is responsible for one thing. This class, speaking from the highest level is conducting everything that exist in the framework core. It provides life to all service providers. But, underneath the simple surface we can find very sophisticated design with complex relationship to and from client and framework. Let’s take a peak inside.

This class is instantiated very early in application life cycle. It happens in start.php file under bootstrap/ folder . And it is initiated by client request. We already can see that it has direct relationship with HTTP protocol and transport layer. To proof take a look at Applicaton constructor - it is expecting Request object as it’s argument:

//
public function __construct(Request $request = null)
{
$this->registerBaseBindings ($request Request::createFromGlobals(

$this->registerBaseServiceProviders();

$this->registerBaseMiddlewares();
}
//

In case there is no explicit Request, constructor will fetch request data from globals. It is internally done by Symfony request class - which is used by Application. Alongside Symfony request class , our Application has relationships with 17 classes. We can see that Application is simply using those classes which are represented as service providers. They create a compositional relationship. On the other hand, our Application is extending Container class (in other words becomes a container ) and implements three interfaces. So already it can become a mass if the Laravel developers didn’t provide a way to organize those relations . It is done through Facade design pattern and Container bindings and resolving of service providers. These patterns deserves a dedicated posts, so let’s get back to more abstract view. One great geeky detail is that Application instance is registered to itself as a service provider in foundation/start.php file.

Application class contains 48 public and 13 protected methods. Those methods can be seen as implementation of Application responsibility to conduct all service providers in a consistent way. Most of ( but not all) Application responsibility is concetrated around service providers and HTTP request. It is not surprising since considering how important are those areas.

At the end of this brief overview try to imagine how would it be to create “headless” Laravel application or application without application ? Download core framework from the github and take a look at tests directory. Creator of Laravel did just that, by testing and simulating real environment - without app layer. Application class is present, but not outside of framework. It is instantiated from the tests. In my opinion developing in this way ( with tests ) is what is separating a real web-programmer from the rest of the world :)

Thanks for reading.

12/15/2013

Laravel architecture layers

Let's talk about Laravel structure. What is it and why having good structure is important - in terms of built in framework architecture.

In this post, I will categorize some Laravel layers as architectural. It may sometimes clash with classic definition of architecture, but it helps me to build good mental model in order to understand framework.

From the highest level, around and inside of Laravel we can reckognize:
  1. Client-server architecture
  2. Laravel specific micro-architecture ( my term )
  3. MVC (model, view, controller)

Client-server architecture lives on a level that is not specific to Laravel, but is implied by the framework. You can implement client-server architecture without Laravel, but opposite is not possible. Web as distributed system uses HTTP protocol as a transport layer to provide content to clients in the client-server model. It is true without any server side processing. Web 1.0 or static web is perfect example. Client-server model as such ( with transport protocol ) underlines whole Laravel implementations. It is implied that we will be writing applications that uses it. Further, we can say that client-server model with HTTP is a kind of edge layer to framework, which simply passes data to framework and give back response in the form of HTML document ( mostly ). Everything else is happening inside  framework - in  another Laravel specific layer. Point of entry to Laravel from client request is a public folder, which is read by server. After Laravel reckognize that request, it will forward data along with path and headers to something that I call Laravel micro-layer. HTTP request is indeed very simple, and there is nothing complicated with it. Best way to think about client-server model is as a transport mechanism that delivers data to some address.

Laravel specific micro-architecture is a middle layer that ties all pieces of framework together and connects client with Laravel. It is represented inside app folder structure. For me, best way to think about this layer is as  internal command-line for Laravel implementation. If you think, it acts like a CLI by calling core API and organizing service providers into meaningful structure. It is possible to interact with core without app layer, but that is not very useful if you are not writing tests. So app layer is a front-end layer of two part internal Laravel architecture. It becomes obvious whan you download core framework from github, without application. Developers spend most of their time in app layer, since it is made for interactiong with Laravel internals. App layer is at the deeper level represented in the form of Application class - a class that server as a glue for all service providers.
Think about service providers as a row power for your application, that comes in many forms. That power should be used in a way that is appropriate for you app. Service providers have their own responsibilities and are already ready to use. Thinking about providers leads us to next layer.

MVC (model, view, controller) is a well known architectural pattern for separating view from data (model). It is implemented in a Laravel through Model, View and Controler folders in application along with their associated classes. As you can guess, MVC classes are provided to application like a service-providers. MVC providers should be considered as primary points of organization and interaction inside application. Everything else is related to MVC. That's why there are dedicated MVC folders in application. If client-server model is responsible for physical separation ( or n-tiered ) MVC represent logical division inside application. Client-server model is exposed to clients while MVC is exposed to developers. All other providers are directly of indirectly related to MVC. For example session, cookies, filesystem, cache, database - these are all persistance mechanisms that finds their place in MVC designed Laravel application. In fact MVC is dominant pattern in the web frameworks, so it is not strange that Laravel is implementating it in its own way.

Everything else beneath MVC and overall architecture belongs to design decisions - how to connect or interact with providers, or how to extend their functionallity. Architecture establishes common structure in which design is possible. With Laravel this is represented through layers described above. I think that it is crucial for serious Laravel developer to become familiar with this layers, in order to master this awesome framework.

Thanks for reading.


12/14/2013

How I moved to PHP thanks to Laravel

Structure is one of the area that brought me a lot of pain while learning programming.

 If I tell you that my first language was Javascript, you'll understand why that's the case. I don't have anything against JS, I love and use that language daily. It had awesome brain-teasing mix of paradigms. Problem is ( as noticed by many developers ) that JS is lacking a good structure. It can especially confuse someone who is introduced to programming with Javascript as a first language ( like me ). With JS you are launhed straight into orbit of closures, prototypes, mutability and incredible dynamism.

That's why, in one moment of my career  I decided to move to some more traditional and better structured language. PHP was somehow natural choice, since I am a web developer. In the beginning ( while PHP was mostly procedural and represented by Wordpress and family ) I couldn't quite grasp it. I was a experienced JS commando that used to shoot with first class functions and throw objects around freely. So PHP wasn't a good choice at that time. And then came newer version of PHP that introduced support for object-oriented and functional  paradigm (a among other goodies ).

Along with the PHP transformation Laravel was born, and I was hooked. I had finally language and framework in which I can approach web development in the way I want ( and programming in general ).  So Laravel is responsible for my PHP adventure. And not just PHP. My knowledge about obligatory design patterns and whole object-oriented paradigm was missing some glue. Sure, thanks to previous experience with JS, in which I had to read about whole programming history and evolution of modern languages, I can flow between PHP code with no real struggle.

And of course, beautifully structured and designed Laravel is a joy to read without writing a single line of code - like a great novel. Class bases languages and frameworks like Laravel helps me to write better organized and more secure code - which is standard for server side applications. So my approach to Laravel is not just from the point of someone who wants to write web-applications and learn API. Through Laravel, I am making progress as a programmer, and I hope I'll be able to contribute to Laravel core soon :)

So this post somehow represents a long introduction to my future writings about Laravel internals, so stay tuned and thanks for reading.


10/22/2013

REST cheat sheet

I created a simple cheasheet table, like every day reminder for creating beautifull rest API-s. So, if you have experience with old PHP routing style in the form of:
"http://host/resource /?id=some_id"

it is time to refresh your skills by moving to more modern approach. Fortunately, REST (Representational state transfer) is supported in all new frameworks like ExpressJS or PHP Laravel.
So this table can help because it can be sometimes confusing to remember which verb belongs to which path.

Here it is:


Thanks for visiting my blog.
Miro

10/21/2013

How to properly understand Javascript language PART 1 ?

Hello;

My first programming language was Javascript. Learning JS without previos knowledge of programming theory ( paradigms, history and language background ) was a very painful process, full of pitfalls and roaming in the dark.  As I can see, a lot of people had a same experience. From my point of view it is because  in JS it is relatively  easy to write applications that looks like a real applications - with the help of large number of  libraries that provides usefull abstractions in the form of their "easy to learn" API.  Canonical example is jQeury - with a minimal code you can have reference to DOM object, without knowing what is happening in the back:

    //
    var elem = $("div")
    //

I am not saying that abstractions are evil, and that we should avoid them. It should be a nightmare to write code without them. After all with the help of abstractions, we are not writing assemby anymore, or in the case of jQuery, cool animations. I want to say that when learning language  starting with libraries like jQuery can cause  unnecessary confusion, which is hard to correct.

This is even more the case with JS, because of it‘s weird combinations of paradigms and idioms. For example, concept of closure  has become trademark of a language, that is very hard to pick without a knowledge about its context, root and origin. To proof, term closure is one of the most searched programming term online, with blogs and even whole sites dedicated to it.
People are really having problem to digest closure. It is not a surprise, because it is one of the hardest programming concept that exist.

After years of struggling with JS I created my mental model about what is Javascript. Of course, it is not just a theory. I am a programmer and the whole point of this post is to better understand Javascript so I can express my self with code.

So lets examine some of the main bulding blocks of JS.

I‘ll start with syntax, since it is very natural to start with when learning new language. Javascript belongs to so called "curly-braces" family of languages, which is mostly influenced by C.
Take a look at the following examples:
    //
    var i;
    for ( i = 0; i < 5, i++){
          console.log("hello");
    };
    int i;
    for ( i = 0; i < 5, i++){
          printf("%s\n","hello");
    };
    //

These two examples are identical, except one cosmetic difference. To write to output, Javascript uses console.log method, which is specific to browser environment, and C uses printf. Their syntatic similarity can also be seen  through code formating that I use in this blog. Both loops are formatted using same pre tag ( <pre class = "brush:js">), which is JS specific. But the output is still well formed, except some minor color differences.  Looking deeper in the languages syntax, there is very, very close relationship between them. I don't want to spend too much time dealing with that topic, since it is covered in more details on other places. To start with syntax comparison read a great Wiki articles: Comparison of programming languages syntax and List of programming languages by type.

The main takeaway from this is: Take some to learn basis of C programming language.  There are tons of great resources and tutorials online. You'll be surprised how much is Javascript influenced by C. In the beginning that influence can be seen as only syntatical, but with experience you'll see how much  have you missed. I became enlightened after learning C.

And that is just a beginning. In the future posts I'll cover other important Javascript  paradigms - first object and then functional.

Miro.


9/16/2013

Linux system calls - fork,exec and pipes.

These days I am passionate about network programming concepts, in order to fully understand Nodejs stack.
I created a small program to demonstrate canonical usage of basic linux system calls - fork, exec and pipes. These calls are used in most network applications and servers. It is heavily commented. Sorry for the code formatting, it is syntax highlighter issue.

#include
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 


// canonical example of fork,pipe and exec.
// it is heavily commented

// main program
int main (int argc, char ** args)
{
    // pipe
    int p[2];
    char buf[5]="\0";
    int pid;

    // do we have a fork ?
    if (!fork()){
        // write to one end of pipe
        write(p[1],"Child writes to pipe\n",22);

        // open a file
        int fd = open("one.js",O_RDWR);
        // read from that file
        read(fd,buf,70);

        //close file descriptor
        close(1);
        // replicate closed descriptro
        int i = dup(0);
        // print usefull message
        printf("Value of fd is: %d\n",i);

        // open new program, and provide some arguments
        execlp("./one","one",buf,NULL);

        // don't forget to exit child process and close open file descriptor
        exit(0);
        close(fd);
    }else{
        printf("Parent reading pipe");
        // read from a pipe
        read(p[0],buf,5);
        // print a pipe content
        printf("%s\n",buf);
        // wait for a child to exit
        wait(NULL);
    }
   return 0;
}
//

Thanx for visiting my blog
Happy Coding :)

9/05/2013

Network programming with sockets

I have to admit, I've moved away from Javascript , and I am spending most of my time in C/C++ together with Unix/Linux programming.
One of awesome things in compiled land :) are native kernel support for socket interface. In case you don't know what are sockets check out this link. Sockets are the basis of Internet, and It is very usefull to become familiar with them. Socket header files are written in C, but there are implementations for all modern languages. Sockets represents low level layer of network stack.
This is my simple implementation of server socket, written in C:

//
#include 
#include 
#include 
#include 
#include 
#include 
#include 

const char message[] = "Yuhuuuuu. Hello From The Server\n";
int main(int argc, char *argv[]) {

    int simpleSocket = 0;
    int simplePort = 0;
    int returnStatus = 0;
    struct sockaddr_in simpleServer;

    if (2 != argc) {

        fprintf(stderr, "Usage: %s \n", argv[0]);
        exit(1);

    }

    printf("%s\%s\n","Listening of port: ",argv[1]);

    simpleSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (simpleSocket == -1) {

        fprintf(stderr, "Could not create a socket!\n");
        exit(1);

    }
    else {
     fprintf(stderr, "Socket created!\n");
    }

    /* retrieve the port number for listening */
    simplePort = atoi(argv[1]);

    /* setup the address structure */
    /* use INADDR_ANY to bind to all local addresses  */
    bzero(&simpleServer, sizeof(simpleServer));
    simpleServer.sin_family = AF_INET;
    simpleServer.sin_addr.s_addr = htonl(INADDR_ANY);
    simpleServer.sin_port = htons(simplePort);

    /*  bind to the address and port with our socket  */
    returnStatus = bind(simpleSocket,(struct sockaddr *)&simpleServer,sizeof(simpleServer));

    if (returnStatus == 0) {
     fprintf(stderr, "Bind completed!\n");
    }
    else {
        fprintf(stderr, "Could not bind to address!\n");
 close(simpleSocket);
 exit(1);
    }

    /* lets listen on the socket for connections      */
    returnStatus = listen(simpleSocket, 5);

    if (returnStatus == -1) {
        fprintf(stderr, "Cannot listen on socket!\n");
 close(simpleSocket);
        exit(1);
    }

    while (1)

    {

        struct sockaddr_in clientName = { 0 };
 int simpleChildSocket = 0;
 int clientNameLength = sizeof(clientName);

 /* wait here */

        simpleChildSocket = accept(simpleSocket,(struct sockaddr *)&clientName, &clientNameLength);

 if (simpleChildSocket == -1) {

            fprintf(stderr, "Cannot accept connections!\n");
     close(simpleSocket);
     exit(1);

 }

        /* handle the new connection request  */
 /* write out our message to the client */
 write(simpleChildSocket, message, strlen(message));
        close(simpleChildSocket);

    }

    close(simpleSocket);
    return 0;
}
//
Happy Coding.

8/17/2013

Bootstrap data with Jade templating engine

Jade is templating engine closely related to expressjs. It is not a surprise, since jade is created by a same author. Jade is heavily influenced by syntax of Ruby and Haml.
There are lot of great features in Jade, that makes dealing with compex views on server side really  smooth. One of them is ability to transfer data directly to html ( jade file ), without additional request.
Let me explain that more. We know that HTTP request are expensive. So it is a good pattern to initially load as more content as possible,  so we don't have to make new requests to server. That is  a winning paradigm that  makes single page web applications so powerful on the client side.  On the client, simply load all the view once and make Ajax request for data if needed.  Since Jade is rendered on the server, this approach is especially useful when application needs data from database for the first load.

With Jade we can easily bootstrap data like this:

//
//here data is plain js object
var data = { "name": "myApp","version":0.0.0,"db":"mongodb"};

// now just render existing view, with data object attached   
app.get("/",function(req,res){
    res.render("home",{obj:data}) 
//

In the previous example data object  was local, contained in the same file as main app file. When we want  to bootstrap data from database, we take same approach when rendering jade template.
Again, data is attached to Jade template. The only difference is that we have to have access to database.

Here is example:
//
exports.queryDB = function (req,res) {
    db.collection("jazz",function (err,collection) {
        collection.find().toArray(function (err,collection) {
            res.render("jazz",{giants:collection});
        });
    });
};
//

Database example is a function that asynchronously query data, due to nature af nodejs native mongodb driver. But when we have data, we can manipulate with it with Jade syntax. For example, to iterate over data object and insert it in the html we can do this:

    // 
    ul
        each giant in giants
            li
                a(href="#{giant["name"]}") #{giant["name"]}
    //


Now we have nice list of jazz giants on our page, bootstrapped on first request.

Thanks for visiting my blog.

8/12/2013

Mongodb and underscorejs - the mean stack

I found a way to combine two very powerful toys that I am playing with :

Mongodb - noSQL database that is shaping web these days and Underscorejs  - which make me fell in love with functional programming.

If you don't know already, mongo is using document/oriented key/value way of storing data in JSON format ( BSON - binary JSON under the hood ).
Underscore has a tons of functions that works with literals like plain JS objects and arrays ( which are basic building blocks of mongo collection ). Also, underscore is environment agnostic. That means that it is not dependent on interfaces like DOM. It is important just to execute underscore functions under Javascripot interpreter. Mongo shell is actually javascript shell, so underscore fits great.

To import JS code in mongo, open your .mongorc.js file, that is located in /home/ directory ( Linux/MacOSx), and place any script inside. It can be whole library, like underscore. Now, from terminal, open mongo shell, and type load (".mongorc.js"). Now all code inside that file is avaliable to mongo documents.

Play yourself and have fun.

Thanks for visiting my blog.


8/11/2013

Design patterns refactored

I did some cleaning and refactoring of my implementations of classic design patterns in coffeescript.
Also I included some variations of existing patterns ( adapter, composite ). There is always more than one way in which we can do same thing ( especially with JS ).

Code is  here

Thanks for visiting my blog.

8/09/2013

Local Search Application

I wrote an application that will search through local data store. It can be easily modified to browse remote db also. By default is searches items in a wiki articles, and uses local array-object as storage.
It is written with the help of jQuery and Coffeescript.
I have to mention that it is not structured in object-oriented or modular way. This code is just a basic idea implemented quickly after inspiration. Inside of bigger application of maybe framework it definitly needs structure, optimization, testing and maybe refactoring.

Code can be found here:

Here is a screenshot:



Thanks for visiting my blog.

8/07/2013

Mediator design pattern with coffeescript

This is second pattern in series of Javascript design patterns implemented with coffeescript.
It can be found here:

Coffeeversion:

//
#Behavioral
#Mediator - classical object-oriented design patterns with Coffeescript
#Global objects are here just for testing in the browser
this.mediator = 
    mediate:(x)->
        if x is "from obj1"
            obj2.receive(x)
        else
            obj1.receive(x)
        
this.obj1 = 
    send:(message)->
        mediator.mediate(message)
    receive:(x)->
        console.log " I am obj1, I just received this message from " + x + " with the help of mediator"

this.obj2 = 
    send:(message)->
        mediator.mediate(message)
    receive:(x)->
        console.log " I am obj2, I just received this message from " + x + " with the help of mediator"
//

Compiled to vanillajs:

//
// Generated by CoffeeScript 1.6.2
(function() {
  this.mediator = {
    mediate: function(x) {
      if (x === "from obj1") {
        return obj2.receive(x);
      } else {
        return obj1.receive(x);
      }
    }
  };

  this.obj1 = {
    send: function(message) {
      return mediator.mediate(message);
    },
    receive: function(x) {
      return console.log(" I am obj1, I just received this message from " + x + " with the help of mediator");
    }
  };

  this.obj2 = {
    send: function(message) {
      return mediator.mediate(message);
    },
    receive: function(x) {
      return console.log(" I am obj2, I just received this message from " + x + " with the help of mediator");
    }
  };

}).call(this);

//

Thanks for visiting my blog.

8/05/2013

superTextArea application - HTML textarea on steroids

I wrote small front-end app, that can be found here: https://github.com/carousel/chatBoySlim

Snapshot:



It is HTML textarea, enhanced with some options for styling and a character counter at the bottom. In the future I have a plan to add support for db communication and web-sockets.

Thanks for visiting my blog.


8/02/2013

Classic design patterns in coffeescript

Today I am going to start a series of posts, in which I want to implement classic OO design patterns with the help of coffeescript.  In case you don't know what is coffeescript and what are the benefits of using it, I highly recommend visiting official coffee site: http://coffeescript.org/, and looking for some tutorials online.

So, to start let's define what is design pattern ?

Wiki article says:
In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design
They were introduced to the OO world by the work of GoF ( gang of four ) group, and their famous book:
 http://www.amazon.com/Design-Patterns-Elements-Object-Oriented-ebook/dp/B000SEIBB8

Patterns in this book are discussed from the point of  classic OO languages ( with strong type system, class-based inheritance ...)
Javascript doesn't support these features, but provide some more flexibile and modern paradigms for solving  problems.
It includes prototype based inheritance, no classes, dynamic type system, no block scope, functions as first class. Writing design patterns with Javascript can be challenging. JS is very flexibile, since same things can be done "in more than one way".

First patterns, that I am going to introduce is  Iterator
  
Implementation in coffeescript:
//
# Behavioral 
# Iterator design pattern with Coffeescript
# Object is explicitly exported in global namespace ( for testing with console.log in the
# browser )
arr = ["begin","middle","end"]

i = 0 
len = arr.length

this.obj = 
    prev:()->
        if arr[i] is "begin"
            obj.end()
            return arr[i]
        arr[--i]

    current:()->
        arr[i]

    next:()->
        if arr[i] is "end"
            obj.begin()
            return arr[i]
        arr[++i]

    begin:()->
        i=0

    end:()->
        i=arr.length-1

//


After compiling in native Javascript:

//
// Generated by CoffeeScript 1.6.2
(function() {
  var arr, i, len;

  arr = ["begin", "middle", "end"];

  i = 0;

  len = arr.length;

  this.obj = {
    prev: function() {
      if (arr[i] === "begin") {
        obj.end();
        return arr[i];
      }
      return arr[--i];
    },
    current: function() {
      return arr[i];
    },
    next: function() {
      if (arr[i] === "end") {
        obj.begin();
        return arr[i];
      }
      return arr[++i];
    },
    begin: function() {
      return i = 0;
    },
    end: function() {
      return i = arr.length - 1;
    }
  };

}).call(this);
//

All code can be foud on my GitHub page
Happy Coding

6/17/2013

Coffeescript + Requirejs

There are great things that can really help you in your development workflow. One of them is Coffeescipt.
Coffeescript alone is a great concept that tries to avoid "bad parts and embrace good parts of Javascript".
But when you combine Coffeescript with one more powerful tool like Requirejs, then nothing can stop you from writins amazing apps.
Since I am using Requirejs for a while, I was trying to find a way not to compile manually Coffee code from the main require file. I found this plugin which lets you write you coffee code, without worry about compiling. How does it work ?

First go to git-plugin page and follow instructions how to install everything. It is pretty straightforward. After that it is possible to write code like this:


//
require([ "modules/cs!modules/iterator","libs/jquery-1.9.1"],  
    (iterator,jquery) ->
    $("button").on("click",(e)->
    console.log iterator.next()
        )
    )
//

This great plugin auromatically compiles coffeescript code to native javascript. It is important to include plugin module properly ( with exclamation point ). The good part is that plugin will load code from the coffee version, and convert it to javascript.

Here is where magic happens:

//
    load: function (name, parentRequire, load, config) {
            var path = parentRequire.toUrl(name + '.coffee'); // plugin is reading file with coffee extension
            fetchText(path, function (text) 
//

Happy Coding

6/14/2013

A taste of functional javascript

There is some real power in functional programming, compared to imperative which is a basis for OOP paradigm. One of them is immutable state.
In a languages that supports state change ( imperative family ) mutability is a double edged sword - you can create awesome control flow ( if you know ) or you can quickly get lost in a jungle of your own variables.
Functional paradigm elegantly avoids state change, by not separating function from the value that is returned. So in FP ( functional programming ) function IS a value. There are some variations and some languages supports state change and mutability to the certain degree, but when we talk about FP we think mostly about functions that are values.

Here is one example of FP. It is written first in Coffeescript, and then in vanilla Javacript:

# data
arr = ["chicken","pig","donkey","horse","cow"]

#main function definition
each = (data,iterator,transform)->
    iterator(data,transform)

#transformer
toUpper=(args)->
    console.log args.toUpperCase() + " farm"

#iterator
iterate = (data,upper)->
    for key,val in data
        upper(key)

#call everything
each(arr,iterate,toUpper)
#

Vanilla Javascript ( compiled ):
// Generated by CoffeeScript 1.6.2
(function() {
  var arr, each, iterate, toUpper;

  arr = ["chicken", "pig", "donkey", "horse", "cow"];

  each = function(data, iterator, transform) {
    return iterator(data, transform);
  };

  toUpper = function(args) {
    return console.log(args.toUpperCase() + " farm");
  };

  iterate = function(data, upper) {
    var key, val, _i, _len, _results;

    _results = [];
    for (val = _i = 0, _len = data.length; _i < _len; val = ++_i) {
      key = data[val];
      _results.push(upper(key));
    }
    return _results;
  };

  each(arr, iterate, toUpper);

}).call(this);
//
Notice the elegance of  functions passing as arguments to other functions, without effecting anything outside them. It is called function composition, and it is the main "sugar" of FP.

Happy Coding


5/28/2013

Awesome TODOMVC project

Look no further - this awesome project will give you everything you need to know about javascript. Take a walk through Todomvc examples and you'll be enlightened. It is incredibly usefull to take a look at just Vanilla.js, as a starting point.That way we can see pure javascript in action - outside of  framework solutions. And later, you can move on to other examples. Authors covered all known and unknown modern javascript framworks and libraries.
Backbone, jQuery, Angularjs, Ember, Dojo, Yui - and even Dart :)
And of course everything starts with pure js.

For example, injecting HTML without templates usage looks like this:

function View() {

  this.defaultTemplate =

'
  • '+'
    ',
    +''
    +''
    +''
    +'
    '+'
  • '; };

    It looks like a string concatenation horror :)

    Or a helper functions, for DOM query, that binds function to global object:

    window.$ = document.querySelectorAll.bind(document);
    window.$$ = document.querySelector.bind(document);
    
    

    Here's a link to TODOMVC GitHub page

    Happy Coding

    5/26/2013

    How to save Backbone collection to the server ?


    Backbone Collection doesn't have save method, it is only avaliable on the Model instances. So how can we save collections to the server ?

    There are couple of workarounds. I found  one very elegant solution, which wraps model around collection. It is opposite to common pattern in which collection is a wrapper around models.

    Here is a basic skeleton of this idea:

    //
    // collection class extended
    var CDShop = Backbone.Collection.extend();
    
    // collection instance 
    var CDShopInstance = new CDShop([
        {
            title: "Blue Train",
            author: "John Coltrane"
        },
        {
            title: "Intercontinental",
            author: "Joe Pass"
        },
        {
            title: "Confirmation",
            author: "Charlie Parker"
        }
    
    ]);
    
    // model class extended
    var MusicShop = Backbone.Model.extend({
        defaults: {
            title: "",
            author: ""
        },
        // passing collection as a property of instance
        model: CDShopInstance,
        // imaginary url 
        urlRoot: "/shop"
    });
    // model instance 
    var musicShopInstance = new MusicShop;
    
    // testing returns three objects from the collection
    console.log(musicShopInstance.model.toJSON());
    
    // now we can save out collection to the server  
    musicShopInstance.save();
    //
    

    Happy Coding.

    5/25/2013

    Bash script helper for fetching remote JS libs

    I created a small bash-script, to help me fetch most freqently used JS libraries for client side development:

    #!/bin/bash
    
    url http://code.jquery.com/jquery-latest.js>jquery.js
    curl https://raw.github.com/documentcloud/underscore/
    master/underscore.js>underscore.js
    curl https://raw.github.com/documentcloud/backbone/
    master/backbone.js>backbone.js
    
    

    Although these libs can be fetched manually, or like a part of for example Yeoman project or Bower, I found that sometimes I don't need all the functionallity that comes with package managers. So this script is ideal for a fast production setup.

    It can be found on my Git repo.

    Happy Coding.

    5/21/2013

    Triggering globally custom events in Backbone

    If you want to implement traditional publish/subscribe pattern, you can do a very cool trick with Backbone custom events model.

    // create a basic model
    var Model = Backbone.Model.extend({
        defaults: {
            color:"red",
            name: "bmw"
        }
    });
    
    // create a view for that model
    var ModelView = Backbone.View.extend({
    tagName: "h4",
    initialize: function(){
        this.render();
    },
    render: function(){
        this.$el.html(this.model.get("color"));
        return this;
    }
    });
    
    // create a route
    var Route = Backbone.Router.extend({
        routes: {
        "home": "showHome"
    },
    showHome: function(){
        Vent.trigger("init");
    }
    });
    
    // create instances
    var model = new Model;
    var modelView = new ModelView({model:model});
    new Route;
    
    // start a history
    Backbone.history.start();
    
    // create a global Vent object, and extend it with Backbone event model (with the help //of underscore.js - which is Backbone dependency ):
    var Vent = _.extend({},Backbone.Events);
    
    // append everything to the DOM, with the help of custom global event:
    Vent.on("init",function(){
    $(document.body).append(modelView.el);
    });
    

    The most important part of this code is attaching custom event handler to the URL route. We made that event  globally accessible, by attaching it to the global Vent object. Vent object is triggering custom init event , which is responsible for appending content the DOM.  We subscribed to that custom Init event  through on method of the global Vent object. This is very basic example, just to show the power of custom events.

    Happy coding.



    5/13/2013

    HTML metamorphosis

    In the beginning, there was that pure markup language, which was fetched from the server, and rendered in the browser:
    <h1>Hello from the HTML</h1>
    

    Hello from the HTML


    Then, someone sad that we should bring some formatting, so it looks nice:
    <h1 style = "color:red">Hello from the HTML</h1>
    

    Hello from the HTML


    And also some Javascript, to make web-sites more dynamic:
    <h1 style = "color:red" onclick=clickMe>Hello from the HTML</h1>
    

    Hello from the HTML


    But, that wass all inline.  So it was good idea to place our CSS and Javascript in a separate files:
    
    
    

    And we had nicely formatted code that could responde to users activity. Sut something was missing - maybe some HTML dissecting on a server side.

    No problem - here comes PHP:
    <h1><?php  echo "Hello from the PHP, embedded in HTML on a server side?></h1>
    
    Hey, we could reuse out HTML!!! Say hello to to templates:
    <h1>{{title}}</h1>
    <p>{{some paragraph text}}</p>
    

    We can even render out HTML on a client side:
    Backbone.View.extend({
    
    render:function(){
        this.$el.html(...);
    };
    
    

    So HTML has been changing it't role on a web quite often, but at the same time remainig dominant  language for building web sites and applications.

    Happy Coding.

    5/05/2013

    Vim vs sublime-text2

    One of the essential tools for a web developer is a code editor. Fortunately, there is a lot of great editors on the market.

    They may be divided on the basis of several criteria:
    • Whether commercial or open software
    • What languages ​​are supported
    • Are they intended for online or desktop editing
    • IDE or a basic a text editor and so on.
    Among them, I personally don't like fancy IDE-s like Dreamweaver of NetBeans. Althought they provide a lot of usefull tools in one window, their core funtionallity is hidden under shiny GUI.
    I like to develope on the basic level without too much use of the mouse and the ability to adjust environment based on my needs.
    For everything else - I use Chrome dev. tools.

    Sublime-text2 and Vim stands in their own in the world of editors.
    Vim is a incredibly powerfull text editor written by Bram Moolenaarand first released publicly in 1991. Part of Vim's power is that it can be extensively customized.
    The learning curve is not so easy, but Vim is intended to be used by dedicated programmers who are willing to spend time learning. After initial difficulties, you discover the world of incredible productivity with a large amount of plugins and custom keyboard mappings. Vim is also completely free.

    On the other hand Sublime-text2 is a new comer in the editors world.

    Some features include:
    • Minimap: a preview of the full source code
    • Ability to select multiple sections of code
    • Multi-panel editing
    • Bookmarks within files
    • Native support for 27 (44 as of Sublime Text 2 beta) programming languages included, with additional available for download
    • Autosave
    • RegEx-based find and replace
    • Fully customizable syntax highlighting
    • Brace matching, autocomplete
    • Support for macros and Python-based plugins
    • Custom key bindings

    One important feature of Sublime is that it has support for Vim commands, through the use of vintage mode.

    In the past weeks I tried to compare these two powerfull editors.
    I am a dedicated Vim user, but I decided to give a chance to Sublime, since it is used by many famous developers.

    I used nonregistered version of Sublime-text2 on Ubuntu 13.04.

    In the end I have to say that I'm not overly thrilled with the Sublime. My conclusion is that all that it offers,  can already be found in Vim. The only obvious advantage I saw is GUI. Vim is despite the use of 256 colors, which extend the range of colors, still attached to the terminal. GVim is of course different, but I'm not using it.
    Sublime GUI is nice and intuitive - but for now that is all.
     All  Vim users have in their fingers  a bunch of custom keyboard mappings. Those mappings is not possible to transfer to Sublime  - even through vintage mode - for me that  is a good reason to stay faitfull to Vim.

    Happy Coding.

    4/10/2013

    Git aliases for bash and zsh

    Tired of typing long shell commands when using git ?

    One of my favourite long example is git log --oneline --graph --decorate - when you want to  see what is happening in you git project ( branches, merging... ) It is very, very long command, that is hard to type, but there is a better solution.

    Depends of type of shell you are using - you can use aliases for often used git commands.  Alias is a shortcut for longer, and more complicated command. Example of built in alias is ls which executes "ls --color_auto".

    To see a list of your aliases just type alias in terminal.
    To temporary create alias, type for example alias server="Python -m SimpleHTTPServer"

    If you want to permanently store alias, open your .bash_profile or .bashrc file and paste same line inside.

    So to change git long --oneline --graph --decorate type alias gl=" git long --oneline --graph --decorate" and you are on.

    If you are a bash user here is a link with bash aliases, that can be copied and pasted in your .bashrc file.

    Since I am using ZSH ( Z shell), here is a link with zsh aliases.
    You'll have to place them in your zshell config file.

    Happy Coding.



    4/07/2013

    How coffeescript makes life easier

    There are really awesome people in JS world. One of them is Jeremy Ashkenas - creator of Backbone.js - great frontend mv* framework; Underscore.js - utility library that makes functional programming possible in js  and Coffeescript - small language that compiles directly to js.

    Coffeescript is basically a dialect of js which adds a syntactic sugar to language. As we know javascript suffers from his bad parts http://www.youtube.com/watch?v=hQVTIJBZook, which made this expressive language unpopular to traditional programmers - especially those who are educated in classical OO way. That includes global variables, prototype inheritance, that keyword...

    Coffeescript tends to bridge that gap, and liberate expressive power of JS by eliminating it's bad parts. In my opinion, it completely succeeded. It is best to write some code, in order to understand.

    First, variable. No need for var keyword anymore:

    var a = "Hello"
    // becomes
    a = "Hello
    
    

    Next, function keyword. Function is one of the most used keyword in js, so it can become hard to type it over and over again. In coffeescript , there is fo function keyword. You just have to do this:

    function fn(){
        // some code
    }
    
    // becomes
    fn = () ->
    
    // and if there is no arguments
    
    fn = ->
    
    

    Prototype keyword is also avoided:

    // instead
    
    Fn.prototype...
    
    // now we use
    
    Fn::some_prop
    
    
    Objects are simplified:

    // No curly braces around object properties:
    myObject =
        prop: "some_prop" // needs proper usage of indentation
    

    Boolean
    // true becomes yes:
    a = yes
    
    // false becomes no:
    b = no
    

    No parentheses:
    // in most cases there is no parentheses
    console.log "Hello Coffee"
    

    In coffee, statements are expressions, so you can write:

    console.log if is true // expression is value
    

    There is much more to discover. Writing code in coffee is like driving a new car after old cluncer. So take a next step in your developer life, and start to compile coffeescript, that's fits perfectly with node and backbone ( coincidence ? )

    Happy Coding.

    Understanding express.js middleware

    Huh;

    I struggled real hard to understand these concepts, which can be confusing, due to node async nature.

    Let's start with wiki definition:
    In its most general sense, middleware iscomputer software that provides services tosoftware applications beyond those available from the operating system.
    Translated to express, middleware is a layer that do all the things beside basic those that node http module offfers.
    Express uses connect functionality for that purpost.  In the beginning express and connect were separated ( connect was dependency ), but lately express includes connect by default.
    So here are some important points to understand, when dealing with middleware and routing in general in expressjs :
    • Node.js itself offers an http module, whose createServer method returns an object that you can use to respond to HTTP requests. That object inherits the http.Server prototype.
    • Connect also offers a createServer method, which returns an object that inherits an extended version of http.Server. Connect's extensions are mainly there to make it easy to plug in middleware. That's why Connect describes itself as a "middleware framework," and is often analogized to Ruby's Rack.
    • Express does to Connect what Connect does to the http module: It offers acreateServer method that extends Connect's Server prototype. So all of the functionality of Connect is there, plus view rendering and a handy DSL for describing routes. Ruby's Sinatra is a good analogy.
    And final tip - it is very important  to include middleware functionality in the right order in your config. file. Here's a link to help http://www.senchalabs.org/connect/

    Happy Coding.


    4/06/2013

    Vim bundle for coffeescript

    Hello internet :)

    I see that this blog is a bit rusty so let's give him some fresh air.
    Along the work, the reason for my inactivity is that I discovered some great resources online that teach about ( take a deep breath, please ):

    - testing ( oh yes I am becoming a real developer )
    - coffeescript  ( now I don't have breath )
    - mongodb ( let your data dance )
    - advanced vim tutorial
    - html5 cool features
    - expressjs, jade...

    I'll write about this later, but for now here are some tips for installing coffeescript plugin on vim. First go to git and pull this to your .vim/bundles folderhttps://github.com/kchmck/vim-coffee-script.git

    Now the problem ofcourse is that settings for these great plugin are avaliable if you use pathogen plugin installer. But if you  use Vundle, which is more advanced that you'll have to make some slight tweeks in your .vimrc  Along with suggestions on forums, how to finally start you coffee syntax in vim, I couldn't do it.
    And finally, magic happened - one more breath please: just put manually this line in your .vimrc file ( in the bundle list ) and it should work:
    Bundle 'vim-coffee-script'
    Happy Coding


    3/14/2013

    LESS - dynamic stylesheet language for developers

    So less saved my soul :) Why ? And what is less ?

    Let's start with our wiki definition:

    LESS is a dynamic stylesheet language designed by Alexis Sellier.

    The most important part of this definition is that less is dynamic stylesheet language.
    Traditionally, CSS belongs to a group of languages called "declarative langugages"Declarative languages are those which describes computation in terms of what needs to be done and not how. That means that your responsibility as a developer is just to declare language constructs, that will be interpreted or compiled later.
    Declarative languages have no notion of memory, which strictly separates them from imperative programming languages.
    HTML and SQL are  examples of widely used declarative languages.
    So you can't for example put a HTML  value in a variable and do some operation on that variable, without a help of imperative language.

    But, with the help of less, we can treat our CSS values dynamically, and create more powerfull formatting for our apps.

    Let't see some examples:

    /*   assign a value to a variable, and use it everywhere */
    
    @color: #eb5200;
    
    p{
        color:@color;
    }
    
    div.main{
        color:@color;
    }
    
    /+ now both p, and div share a same color value */
    
    

    Mixin is another powerfull feature of less:

    /*basic class with variable value*/
    .some_class{
        color:@color;
    }
    
    /*extend div.main class (mixin) with .some_class properties */
    div.main{
        .some_class;
    }
    

    There are more advanced topics like nesting, mixpaths, arguments and functions which you can read here.

    Css is more of a designers stuff.  I am not a designer,
     so less helped me  to do formatting part of development in  a more programmatic fashion.

    Happy Coding.

    3/13/2013

    color mixer app updated with rgb to hex converter

    I changed a design of my color-mixer app, by adding rgb to hex convertor. Hex values can be seen and copied from the input field.

    Here's a new code:

    Html:
    Red: Green: Blue:

    And js:

    // set body to listen for change event
    document.body.addEventListener("change",function(){
    
        var red,green,blue,aaa,convert;
    
        //query dom elements
        red = document.querySelectorAll("input")[0];
        green = document.querySelectorAll("input")[1];
        blue = document.querySelectorAll("input")[2];
        val = [red.value,green.value,blue.value];
    
        //component to hex
        function compToHex(c) {
            var hex = c.toString(16);
                return hex.length == 1 ? "0" + hex : hex;
            };
    
        //rgb to hex
        function rgbToHex(a,b,c) {
                return "#" + compToHex(a) + compToHex(b) + compToHex(c);
            };
    
            //update input fields and page background
            convert = rgbToHex(parseInt(val[0]),parseInt(val[1]),parseInt(val[2]));
            document.body.style.background = convert;
            var h = document.getElementById("hex");
            h.value = convert;
    });
    
    

    Happy Coding

    3/11/2013

    Chrome snippet extension

    Since I am dedicated chrome developer  tools user ( especially console ), there are cases in which I need to type a long lines of repeating code.
    Chrome has a nice snippet feature, which is hidden under settings icon.  To enable it just go to settings button ( in the bottom right corner ), then choose experiments and check the snippets support checkbox.

    Now, when you open sources panel, there is a snippet area. Just create new snippet ( right click to open small menu ), enter you code and have fun.

    Important note: you may have experimental extensions disabled. If so, just type about:flag in the address bar, and find experimental extensions api, which needs to be enabled.

    Here is a screenshot from my snippet with  console panel opened:


    Happy Coding

    3/10/2013

    the power of vim folding

    Code folding is very powerful technique, which is not so obvious. But when you see how folding can help you organize your code ( especially long nestings ) you'll start using immediately.

    Of course, vim has a great support for folding.

    Here are some commands ( in normal mode)
    zf - create folding ( after selecting in visual mode)
    za - toggle foldings
    zc - fold close
    zo - fold open
    zE - remove all folding 
    Here are some screencasts of folding a long function ( 100 lines of code ). To see a flow of folding, select an image, and then blogger will open nice gallery. After that just scroll througn images with middle mouse wheel.













































    Happy Coding

    Cool HTML5 color slider with vanilla javascript (chrome only)

    HTML5 is full of surprises. Here is a cool demo how to create custom color slider with only HTML5 and javaScript. But before we dive into creating slider, there are some thing that needs to be sad about HTML5.

    First, HTML5 is job in progress. It is not standardized yet. That leads us to one big issue - browser support. Before doing some actuall work be sure to test in all modern browsers.
    Here is one great resource that can help:

    http://caniuse.com/#compare=ie+5.5,ie+6,ie+7,ie+8,ie+9,ie+10

    Next, HTML5 together with CSS3  is bringing new refreshment to 20 year old technology. Now HTML is not just a markup language, which we use to outline our document. It is a platform for creating powerfull web applications. Some of main changes includes new structural tags ( header, section,artice ...) that are semantically focused and closer to users and clients. Also, there are new application specific tags ( video,audio... ), new form  elements ( email,range,color...).

    Let's see out example. First html:


    <ol>
    
    <li><input type = "range" value = "0" id = "r" min = "0" max = "255"></li> 
    <li><input type = "range" value = "0" id = "g" min = "0" max = "255"></li>
    <li><input type = "range" value = "0" id = "b" min = "0" max = "255"></li>
    
    </ol>
    
    

    Put this html snippet somewhere inside body.

    Now javascript. Place script in external file or between script tags:

    // lets use new dom selectors
    var r = document.querySelectorAll("input")[0];
    var g = document.querySelectorAll("input")[1];
    var b = document.querySelectorAll("input")[2];
    
    // and functionality
    // adding change event ( which fires on value change of input elements ) to body
    document.body.addEventListener("change",function(){
        document.body.style.background = "rgb("
        + [r.value,g.value,b.value].join(",") // join values of sliders and update background color
        + ")";
    });
    

    Now, when you move the slider, background color of your page shoud change also.

    Happy Coding.

    3/09/2013

    mixins pattern


    Javascript doesn't have support for muptiple inheritance.That means that objects by default can inherite only from one class (constructor). But because of expressive power of language, we can easily implement multiple inheritance with mixin pattern.

    At the begining, let't quote Stoyan Stefanov from his book Javascript patterns:

    Code reuse is the goal - inheritance is just one of options throughout we can achive code reuse

    Lets see some code:

    function mix() {// no parameters specified
        var arg, prop, child = {};
        for (arg = 0; arg < arguments.length; arg += 1) {// length
            for (prop in arguments[arg]) {// browse properties
                if (arguments[arg].hasOwnProperty(prop)) {// check if properties exists
                    child[prop] = arguments[arg][prop]; //copy
                }
            }
        }
    return child;
    }
    
    // call a function with mixed objects as arguments
    var cake = mix(
        {eggs: 2, large: true},
        {butter: 1, salted: true},
        {flour: "3 cups"},
        {sugar: "sure!"}
    );
    
    
    As you can see, it is simple to copy properties with this  pattern, and emulate multiple inheritance.  One interesting thing in this pattern is that in function mix there are no paramaters, all the job is done with arguments.  First we detect arguments length, then check  if propeties exists and finally we copy them into new object. This example is also great because it uses nested loops and conditions.

    Happy Coding.




    3/01/2013

    Fun with type casting in javascript

    Let's have some fun with type casting in javascript today :

    Do you know what is:

    "2" // string as we know
    
    

    what about:

    +"2" // number
    
    

    but wait, what is this:

    1 + +"2" //  3
    1 - - "3" // 4
    
    

    boolean:

    +true // 1
    +false // 0
    -true // -1
    -false // 0
    !!true // true
    !!false // false
    
    

    meet miss tilde:

    ~true // -2
    ~~true // 1
    ~false // -1
    ~~false // 0
    1 - ~true // 3
    1 + ~~false // 1
    
    

    a real fun:

    - ~ -2 // -1
    - ~false //1
    - ~0 // 1
    ! ~ -2 // false
    ! ~ -1 //true
    
    


    You just saw hidden treasure of our favourite language.

    Happy Coding :)


    2/28/2013

    Rethinking about function objects in javascript

    Traditional way of learning about functions in javascript is that we look at  them as objects with properties and methods.

    So you can write:

    // function declaration
    function car(){
        // some code
    };
    
    // add properties to car function
    car.color = function(color){
        return "This car color is: " + color;
    };
    
    car.color("blue")  // returns "This car color is blue"
    
    

    Now you have static property of car function/object.

    That is something you can't find in other popular languages. In other languages,  functions are usually treated as behaviour attached to some class or object.That way, they are just serving one purpose  in the kingdom of the nouns.


    The role of functions ( as objects) in javascript is pretty non conventional and unusuall. Many developers are having trouble seeing them as objects.

    But other then that ( which is considered strange and liberal ) , there is one more  definition which brings totally new way of thinking  about functions.
    And that is where the real power of language lives.

    They can be seen as behaviour that caries data instead of data that caries behavoiur. It is a very important concept that must be well understood.

    Lets look at code:

    // function declaration with nested func inside
    function car(){
        var color = "blue"
    
        return function(){
            return "This car color is: " + color;
        };
    
    };
    
    // call
    
    var color = car();
    
    color() // returns "This car color is blue";
    
    


    So we have exactly same result, but what is the difference ?  This time instead of assigning static properties to function object, we created closure with nested function. That closure behaves as object,  memorizing properties from the parent scope. You can put everything in closure - objects, functions. All kind of data. Now behaviour ( nested function ) carries data around from it's environment.


    Happy coding.




    2/26/2013

    jQuery.fn.init constructor - this is where the fun begins

    Below you can see a point of entrance into the jQuery API - fn.init constructor:

    // jQuery.fn.init constructor
    
    init:function ( selector, context, rootjQuery ) {
      var match, elem, ret, doc;
    
      // Handle $(""), $(null), $(undefined), $(false)
      if ( !selector ) {
       return this;
      }
    
      // Handle $(DOMElement)
      if ( selector.nodeType ) {
       this.context = this[0] = selector;
       this.length = 1;
       return this;
      }
    
      // Handle HTML strings
      if ( typeof selector === "string" ) {
       if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
        // Assume that strings that start and end with <> are HTML and skip the regex check
        match = [ null, selector, null ];
    
       } else {
        match = rquickExpr.exec( selector );
       }
    
       // Match html or make sure no context is specified for #id
       if ( match && (match[1] || !context) ) {
    
        // HANDLE: $(html) -> $(array)
        if ( match[1] ) {
         context = context instanceof jQuery ? context[0] : context;
         doc = ( context && context.nodeType ? context.ownerDocument || context : document );
    
         // scripts is true for back-compat
         selector = jQuery.parseHTML( match[1], doc, true );
         if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
          this.attr.call( selector, context, true );
         }
    
         return jQuery.merge( this, selector );
    
        // HANDLE: $(#id)
        } else {
         elem = document.getElementById( match[2] );
    
         // Check parentNode to catch when Blackberry 4.6 returns
         // nodes that are no longer in the document #6963
         if ( elem && elem.parentNode ) {
          // Handle the case where IE and Opera return items
          // by name instead of ID
          if ( elem.id !== match[2] ) {
           return rootjQuery.find( selector );
          }
    
          // Otherwise, we inject the element directly into the jQuery object
          this.length = 1;
          this[0] = elem;
         }
    
         this.context = document;
         this.selector = selector;
         return this;
        }
    
       // HANDLE: $(expr, $(...))
       } else if ( !context || context.jquery ) {
        return ( context || rootjQuery ).find( selector );
    
       // HANDLE: $(expr, context)
       // (which is just equivalent to: $(context).find(expr)
       } else {
        return this.constructor( context ).find( selector );
       }
    
      // HANDLE: $(function)
      // Shortcut for document ready
      } else if ( jQuery.isFunction( selector ) ) {
       return rootjQuery.ready( selector );
      }
    
      if ( selector.selector !== undefined ) {
       this.selector = selector.selector;
       this.context = selector.context;
      }
    
      return jQuery.makeArray( selector, this );
     }
     

     When you call $ function for example:

    // call $ function with one argument ( html p element as a string ):
    
    $("p")
    
    
    You are calling a constructor that will return p element, wrapped in new jQuery object. That returned object is stored in prototype property of init constructor, so all instances will automatically inherit all properties and methods from it.

    Main responsibilities of init constructor function are:
    1. to receive argument provided by API (application programming interface ) user ( usually developer )
    2. to handle response based on type of argument. - -for example handle arguments as variables (document.body ) or as strings ("div")
    3. to wrap argument into new jQuery object and return as array ( in javascript arrays are objects too )
    4. to provide subclass relationship and inheritance chain.

    Last point is very confusing for many people. There is a question  why jQuery is using external ( static ) fn.init property to enable inheritance part ? If you look at code, you can notice that jQuery.prototype and jQuery.fn.init.prototype are referencinng same object. If you add some properties or methods to $.prototype object, it will be automatically added to all instances of init constructor.  So jQuery has two constructors nested. You can call main function  with keyword new, (new $("selector") or more commonly without keyword ($("selector")).

    After that,  chosen element is ready for traversing, manipulation, effects and all other goodies provided by jQuery init prototype object  - which is a property of init constructor function.

    It is just one part of jQuery story. Other part includes helper functions like Ajax, extend, each, data... They represent advanced part of library and they are usually called and connected with the rest of the code in jQuery implementation, but can be used as standalone methods.
    Each method can be used to iterate over some custom collection ( object or array ), but it can be found as a part of lot of internal functions and methods.

    Happy Coding.

    2/24/2013

    A closer look at operator precedence

    Classic definition of order of precedence from the Wiki is, as follows:
    In mathematics and computer programming, the order of operations (sometimes called operator precedence) is a rule used to clarify which procedures should be performed first in a given mathematical expression

    You can find this and similar definitions in all beginner programming books, along with tables that shows it graphically.
    Here is a one such table. I like it because it is compressed, and it shows all important operators in C, grouped by types related precedence. It is not so visually nice, but it will do the job. There are more detailed tables, specific to different languages (  for example here you can't find dot ( "." ) operator from the OOP paradigm ...), but I think that we  should first learn the basics:


    () [] -> .
    ! ~ ++ -- + - * & sizeof
    * / %
    + -
    << >>
    < <= >= >
    == !=
    &
    ^
    |
    &&
    ||
    ?:
    = += -= *= /= %= &= ^= |= <<= >>=
    ,

    Closely related with precedence is associativity  - which describes how operators of the same precedence are grouped in the absence of parentheses. There is left or right associativity.


    Now that you know the basics, there are some interesting things that can be learned by looking in this table.

    For example why operator of assignment has a lowest priority ? And why in OOP paradigm operator dot ( "." ) has highest priority ?
    That's because dot operator is potentially capable to give one of the highest level of abstraction to data, compared to all other operators. What does it mean ?

    Well,  if we declare and define object in javascript like this:


    // object literal
    var obj = {};
    
    
    You are actually providing opportunity to program to move further from basic  values which are building blocks of programs. As we know, all expression must be evaluated before usage. So if you have expression in classic math:
     5 +  10 * 20 
    We know that we are talking about evaluation which leads to some result.

    Same thing is happening in programming. All expressions needs to be evaluated to some basic values, in order to work with them. Lets see example in javacript:


    //object literal with one property
    var obj= {
    
        prop: "Hello Operators"
    
        }
    
    
    If we want to access obj prop property, we'll have to use our dot (".") operator. Why ? Because prop is abstracted or moved away more from the language that computer understand.
    So it needs to be evaluated to some basic ground, before it can be used.

    I am talking here about built in data types in most popular  languages, which serves as a point of evaluation. On a deeper level, everything gets translated to binary, but that is not important for this topic.

    What about assignment operator ( = ) ? Well, in table it has one of the lowest priority. Why is that ? Assignment is directly connected with memory in most imperative style programming languages. In fact, when you assign a value to some variable, using assignment operator, you are creating a memory address and a space for that varible on a machine level. That variable is carrying a value of some basic type. We can say that assignment operator is standing last in line, waiting all operations to be done, before it can assign a value to some name. If obj.prop appears somewhere else in a code for example:


    
    // conditional statement that evaluates  property value
    if ( obj.prop) {
    
        // do something
    
    }
    
    
    


    It will again be evaluated to it's actual value ( "Hello Operators" string ).

    In this post I looked at two extreme positions in a table of operator precedence. By comparing their behaviour, we can see why they have different precedence, and also what is happening with all other operators. They  appear everywhere in language, and they are connective tissue of values. So it is important to be familiar with them more then it can be found in classic examples. Here I tried to fill some gaps, which were missing for me to completely understand them.

    I hope it will help you also.

    Happy Coding.







    2/23/2013

    Recursion with palindrome example

    Today I found a great example of recursion function with palindrome word.  If you don't know what is palindrome, here is a wiki quote:
    palindrome is a word, phrase, number, or other sequence of units that may be read the same way in either direction, with general allowances for adjustments to punctuation andword dividers.
    Recursion function:

    
    // recursive function declaration
    
    function isPalindrome(text){ if (text.length <= 1) return true;
        if (text.charAt(0) != text.charAt(text.length -1)) return false;
        return isPalindrome(text.substr(1,text.length -2));
    };
    
    
    Now, if try to call recursive function with some palindrome, for example madam you'll get true, and madams will return false. Inner algorithm is fun and brain teasing.

    2/22/2013

    JSLint - javascript code-quality tool from terminal

    If you wanna make art of your code, take a look at JSLint. It is a javascript code quality tool, created by Douglas Crockford - world famous js evangelist and author.

    Here is a way how to download it with NPM ( node package manager ) and test your code:

    In terminal type :
    sudo npm install jslint -g

    I suppose you know what is nodejs, and you that are using linux or mac.
    If you are on windows take a look around, there is a guide somewhere, I am sure.
    Next, create a js file, and put some code inside. I am sure that you'll be surprised with the result after testing.  Now move to that folder ( where the file is ) and type jslint name of file.js and learn from the results.

    Update to post:

    If you are using Vim with syntastic plugin, than JSLint which you installed globally ( with -g flag ) will check all your js script during coding in vim.

    Happy Coding.

    2/20/2013

    What is a helper method ?

    You probably heard about them, and use them but you didn't know that. Helper methods are usually  provided by the library. Underscore.js _.each function is widely used helper method throught many libraries.

    Here's a nice definiton, from the classic perspective:

    Helpers are one consequence of composed methods. If you are going to divide big methods into several smaller ones, you need those smaller methods. These are the helpers. Their purpose is to make larger-scale computations more readable by hiding temporarily irrelevant details and giving you a chance to express your intention through the name of the method. Helpers are typically declared private, moving to protected if the class is intended to be refined by subclassing.
     And example from Backbone.js library:

     
     
      function (attributes, options) {
        var defaults;
        var attrs = attributes || {};
        this.cid = _.uniqueId('c');
        this.attributes = {};
        if (options && options.collection) this.collection = options.collection;
        if (options && options.parse) attrs = this.parse(attrs, options) || {};
        if (defaults = _.result(this, 'defaults')) {
          attrs = _.defaults({}, attrs, defaults);
        }
        this.set(attrs, options);
        this.changed = {};
        this.initialize.apply(this, arguments);
      }
    
    Above, you can see Backbone.Model method, which needs to be instantiated. Model is full of properties, but it is not ment to serve as constructor. For that purpose we use Backbone.Model.extend method, which simply helps establishing inheritance and providing bridge between Model and instance:
    function (protoProps, staticProps) {
        var parent = this;
        var child;
    
        // The constructor function for the new subclass is either defined by you
        // (the "constructor" property in your `extend` definition), or defaulted
        // by us to simply call the parent's constructor.
        if (protoProps && _.has(protoProps, 'constructor')) {
          child = protoProps.constructor;
        } else {
          child = function(){ return parent.apply(this, arguments); };
        }
    
        // Add static properties to the constructor function, if supplied.
        _.extend(child, parent, staticProps);
    
        // Set the prototype chain to inherit from `parent`, without calling
        // `parent`'s constructor function.
        var Surrogate = function(){ this.constructor = child; };
        Surrogate.prototype = parent.prototype;
        child.prototype = new Surrogate;
    
        // Add prototype properties (instance properties) to the subclass,
        // if supplied.
        if (protoProps) _.extend(child.prototype, protoProps);
    
        // Set a convenience property in case the parent's prototype is needed
        // later.
        child.__super__ = parent.prototype;
    
        return child;
      }
    
    
    It is possible to keep together Model and extend. It is not good design approach, cause we will sacrifice modular approach (among others pitfalls). Choosing to separate main method on two loose coupled parts, we are making extend methond reusable to other parts of our code. As you can see, Backbone authors did exactly that - you can extend Model,View,Router,History and Collection with one helper function.

    Happy Coding

    2/19/2013

    Recursion demystified

    Recursion is one of the main programming construct, that is very powerfull but sometimes it is not easy to understand.
    I found one great example of recursive call:

    
    // self invoking recursive function
    
    (function foo(i) {
        if (i === 3) {
            return;
        }
        else {
            foo(++i);
        };
        console.log(i);
    }(0));
    
    Copy and paste it in chrome dev tools or in js interpreted environment. As  you can see it's not fibonacci, which is often used. This example is more straight-forward and simpler.

    The output is 3,2,1.  It shows the way recursion works.
    In short here is what is happening  - the inner function keeps calling outer function untill it reaches base case.
    What is base case ? It is a number of calls which must be provided, usually expressed like a condition. If there is no base case, infinite loop will happen, which is not what we want. Since inner and outer function are same, we have a situation in which a function calls ifself. Foo inside will keep calling itself with provided arguments until it reaches base case.
    And now important part: do you wonder why the output is inverted ? What don't we have 1,2,3 instead of 3,2,1 ?
    That's because inner foo function is keeping results of calculation ( incrementing i ) somewhere in memory , but it can't provide output since it is called over and over again untill it reaches base case. That memory is called recursive stack, and it is a form of data structure, in which last data entrance is removed of called first. So when inner foo finally reaches base case, it is ready to "unwound" memory stack from the last to the first result giving 3,2,1 output.

    Recursion is widely used in functional programming paradigm and it is considered for alternative to iteration. 

    2/18/2013

    Underscore js rocks

    Hello World;

    It's time for enlightnement.
    Let me introduce you Underscore.js. It's a  small js library that provides lot of functional programming features, which is missing in native js implementations.

    How to install it? Very simply - just copy file from this page
    http://underscorejs.org/

    or from git:
    https://github.com/documentcloud/underscore

    Put a file in you project folder, link to  it from the main page. In my case it looks like this:

    
    // link to your underscore file
    
    
    
    
    Now you should have new global js object named Backbone. Test it in chrome dev.tools:

    
    // examine Backbone object
    
        dir(Backbone);
    
    
    And finally lets see underscore in action (btw shorthand for library is_" ) with one example:

       Range function:

    
    // assign the result to variable range
    
        var range = _.range(5,10,2)
    
    // log in developer tools
    
        console.log(range);
    
    
             Output is [5,7,9]

    Guess what is happening ?
    Hint: pay attention to third paramater.

    Underscorejs if full of utility functions that you can find in languages like Python of PHP. It is bringing more power and flexibility to Javascript and to your projects in general.
    Also, it is a important part of jQuery and Backbone.
    Feel free to experiment, it is fun with this great library.

    Happy Coding.

    2/16/2013

    more vim tips & tricks

    These days I'm digging deeper into wonderfull world of our favourite editor .
    So here's what I discover:

    Nerd commenter plugin

    commands:
        - ,cc  comment a line of selected text
        - ,ca change comment style ( nerd will recognize language )
        - ,ci toggle comment
     
    There is more ofcourse. Very helpfull plugin for production.
    Here is a link for downloads.

    http://www.vim.org/scripts/script.php?script_id=1218

    Easy motion

    basic commands:
        - ,,w mark a text so you can easily skip whereever you want
        - ,,k mark  backword

      http://www.vim.org/scripts/script.php?script_id=3526

    Happy coding