Category Archives: Javascript

Best Practice to Build a Backbone.js App

backbone-300x53I’m going to show my way of building a Backbone.js application architecture. But first I will tell you why I’m going to do that.

There is no one best way to build a Backbone.js app, Backbone.js is so flexible that you can write a good application is many ways.

Backbone.js has a lot of critics. The most obvious of all is the claim that there is no one straight forward way to build a Backbone.js app, more than one recipe exist. Every individual is doing it a little bit different. In my opinion that is a good thing.

What You Already Need To Know

This is a basic tutorial for creating an application architecture but you should already know what is a backbone model, collection, view and how to create them.

Freedom of Coding

You can built an app in any way You want. That can be a bad thing if you are not such a good developer. So I will say to you that if you are planing to be a mediocre developer, don’t develop in Backbone.js, it’s not that it is hard, it’s actually very easy. So easy that it will let you do stupid things, similar to PHP.

Gradually Adaptation

Backbone.js is a very versatile tool, and as such you can basically do whatever you want. One of these perks is the ability to convert your app gradually to Backbone.js. Yes! it is not a framework, you can play with a little feature and you can migrate your app bit by bit.

POP, or Power Of Plugins

I’m not talking about Backbone Plugins… those exist and they are great. I’m referring to any JavaScript plugin that exist. want to use the funky jQuery dropdown plugin that you saw? You can! Or what about this beautiful bootstrap tooltip plugin? You can.

In fact it is very easy to use any plugin and embed it in your Backbone.js application. This feature was the most important one for me.

Application Structure

Ok, after the ‘why’ let’s move on to the ‘how’, Every Backbone.js app that I’m building has the same structure layout. It does not have to be in that structure, I just found out that most of the time that structure is a best practice for me.

I’m using one global variable that holds the entire application. Usually I call it ‘app’.

here is the structure of the app object:

As you see under the app object there is another object called ‘bb’ that is my short to Backbone, all my Backbone objects will exist under the ‘bb’ object.

Under the ‘bb’ object there are three types of objects that start with an uppercase

  • Models
  • Collections
  • Views

And as you can imagine, all of the models will be under ‘’, collection under ‘’  and views under ‘’

The actual instances of models will be under ‘app.models’, same for collections and views.

Creating a New Model Object

When creating a new model, just extend the ‘’ object:

It is best practice that the object name will also start with an uppercase, this way it will be easy to distinguish between objects and instances.

Creating a New Model Object Instance

Creating an object instance is simple:

The same process apply to collections and views.

Raw Data

Preserving data after manipulation could be easy when you have a dedicated object for it. Want to create data that is not part of your models / collections / views? In those cases I save the data under ‘’ and ‘’. This is not a good idea if you have a huge amount of data – the browser have a size limit and with a humongous amount of data it could crash.

JavaScript Context is Actually Easy to Understand

js-150x150One of the most misunderstood concepts of JavaScript is the context topic. When saying context I’m referring to the ‘this’ keyword inside a function.
Now let’s break that down:

If it is a constructor than the ‘this’ keyword will refer to the newly created object.
So when creating an object with the ‘new’ keyword the context of the ‘this’ keyword is the new object that was created. But if the function would have been called without the ‘new’ keyword than the context would be the global context meaning the global ‘window’ object

On an object the context is the object the function is executed on. Sounds confusing? A simple example will clear that out:

That is it! It is simple as that. So, why the confusion? Things can go a bit more complex when we want to use a different context than the current one. Let’s look at an example:

I used  the context var here because that inside the ‘dat’ function we have a new context so if we used the this keyword instead of the context variable then it would refer to ‘obj.doo’ instead of just ‘obj’

Another exception of context is the ability to control the context inside a function. Using the call and apply method of JavaScript we can set the context:

The call function first parameter is the context that will be available as the this keyword inside the called function. the rest of the parameters – will be the original function parameters:

The difference between call and apply is the way the parameters are passed:

These two calls are equivalent, the apply function parameters are just passed as an array. Why do we need that? well, sometimes we have the data as an array and this will save as the conversion, no other difference besides that.

Hope this was clear… Have Questions? contact me! or post a comment

GRUNT – JavaScript Build Tool For Everyone

It doesn’t matter if you are a high level developer or


a newbie – Grunt can help you. I will share a few practical ways

Minify your codethat I use Grunt, although I can for sure do a lot more with Grunt than just those solutions that I will discuss I will only discuss only a few of my favorites. Also I am still in the learning process of all of the benefits of Grunt, so if you have a usage that you think is important and is not listed here, please share! All of my current usages for Grunt is for static resources.

With Grunt you can easily minify your code into a destination file. The most common way to minify a file with Grunt is to use Uglify.js. there is a lot of information on the Grunt website on how to get started.

Combine a few JavaScript files

With Uglify you can combine a few files into one file – that is great for configuration files. If you have different configuration values on your development server than your production server – just make all your configurations on a separate file and combine it with Grunt. The build will be per server.

There are a lot of ways to handle configuration in JavaScript. The most obvious is to just put it in the script without thinking about it too much. That solution is good only if you test everything on production, but for those sane developers like us that want to test our scripts on multiple environments we need a good way to easily move our scripts from one environment to the other. With Grunt it is easy to do so – use a settings file that is combined during the build process


you can put JSLint as part of the build process, personally I don’t use that feature since I use JSLint directly into my IDE, but that can be useful for other people.


We can integrate our tests with the Grunt build. This is extremely useful since I can integrate the testing process directly to the build process and when the test is failing – I will get an immediate feedback.

Reformatting code

remove all of your debugging code on the build, that way no accidental console.log statements on the real script.

How to install?

A great in depth manual is in the Grunt website. It is depended on Node.js.

Getting to Know JavaScript Scoping

js-150x150Becoming a Pro in JavaScript requires a few capabilities, one of the most important ones, is understanding JavaScript variable scoping. A lot of developers that came from a different programming language bang their head in the wall often until they fully understand JavaScript scoping mechanism. Let’s start:

What is Scoping?

scope-200x300You can’t access everything from anywhere. Each function and variable in JavaScript has a scope, you may have not been aware to the existence of the scope, but it does exist. A scope is basically an access mechanism to an object, function or variable. if you can access an object than you are in the object scope, and If you have no access, you are out of scope. There is a scope that is accessible from anywhere – the global scope. but let’s first start with the simple scope mechanism – the function scope.

Function Scope

In JavaScript – the scope is changed only in functions and not in any curly braces {..} like in a lot of other languages. so if we look at the next example we can see that we can’t access the ‘bar’ variable since we try to access it outside the function and that means that we try to access a variable out of the scope and that is not possible so the alert will throw a “ReferenceError: bar is not defined”.

The function ‘bar’ has it’s own scope and anything that will be defined in the function could not be accessed outside of the function.

Global Scope

The global scope can be accessed from everywhere, as a rule of thumb there should be as few global scope variable as possible. A lot of global variables can cause conflicts in complex applications.

Access from everywhere means that you can access the global scope from any portion of your code, at any time. When a variable is scoped globally it can also be accessed through the ‘window’ object, I mention that because of the next example:

There are mainly 3 ways to declare a variable in the global scope:

  • Each variable that will be declared in the main script, that means not inside a function will be scoped in the global scope

  • Declaring a variable without using the ‘var’ keyword will cause the variable to be scoped globally, no matter where it was declared. that is a huge pitfall for a lot of beginners.

  • Adding a property directly to the ‘window’ object - = “hello”

From the above example we can learn that although the scoped var foo in the function is now “hello” the original foo variable is still accessible through the window object who holds all the global variables.

As I said before, any variable or function that is declared outside a function or object will be scoped automatically in the global scope.

Always Declare your Variables

When declaring a variable – it should always be prepended with “var”, not doing this will cause the variable to be scoped globally. that can cause an unexpected behavior.

Look at the next example in order to understand how forgetting to prepend a variable with the ‘var’ keyword will cause the ‘bar’ variable to be scoped globally :

To better understand the problem that could arise from this, take a look at the next example:

because ‘i’ is used in foo in the global scope, the ‘var’ was not used… than the alert will not say that “i is true” because ‘i’ is actually equals to zero because we called the foo() function before our if.

so to summarize how you should use any var in a function, don’t use it in a global scope like that:

You might think it is better to do it like this:

but you will be wrong, well, at least not 100% right..
The best way is to declare it at the beginning of the scope:


but… why? well, it is the preferred way because of what is called Hoisting.

JavaScript Hoisting

Hoisting is a strange behavior when you first hearing about it, what it means is that any variables / function that belong to the current scope will be declared at the beginning of the scope. the difference between a variable and a function hoisting is that the function will have a value in the beginning of the scope while a variable will be undefined.

Why is that something that is important to know? take a look at the next example:

you would think that the output will first log ‘hello’ and ‘world’ but it will actually will log ‘undefined’ and ‘world’.
why? Hoisting! that is why… with hoisting your code will actually be interpreted as:

So in order to not be surprised with unexpected behavior – it will be a good idea to always declare any variable that is used in the scope at the beginning of the scope.

Unlike variables, functions have their value when called before their declaration. You can see that from the last example where we called the ‘bar’ function before it was declared, That was possible because of hoisting that was interpreted into:


Scoping in JavaScript can be tricky. but all the common pitfalls can be avoided with the coding conventions I presented – declare all scoped variable at the beginning of the scope and prepend all variable declaration with the ‘var’ keyword.


You should use Underscore.js

I must admit, the first time i encountered Underscore.js i didn’t get it. All I saw is a bunch of functions…

Let me start by saying that you want to use underscore.js, you might don’t know it yet but you want to.

Underscore.js is exactly what it seems – it is bunch of functions. But these collection of functions have one true goal – to make you put your attention on developing your logic and make some operations trivial. If you are familiar with jQuery, than you probably know the benefits of how it is simplifying the DOM manipulation, Underscore.js is similar to that in a manner that it is simplifying data manipulation in JavaScript.

Underscore give your JavaScript coding a turbo engine by giving you functions that let you sort and filter your data really easily.

The easiest way to understand Underscore.js is by an example:

Let’s say that you have a collection (an array of JavaScript objects of the same kind) of student grades and you want to give student id ‘15’ an extra 10 points.

In pure JavaScript it could look like this

In Underscore.js it will look like something like this:

At first it looks a bit weird to use the ‘_’ as an object, but if you got used to the jquery ‘$’ you will get used to this one too.

The findWhere function will go over the collection and will return the first occurrence of the the student with an ‘id’ of ‘15’, this is really efficient because if you have 1,000,000 students – it does not have to go over all of them – as soon as it finds it – it will stop the search.

besides the performance boost and the fact that it was easier to write you can see that it is easier to read – that is an awesome bonus because six month from now when you want to add a cool feature to your code you can understand it better because it is more readable.

Another example is to create a function that returns how many students got a grade that is higher than 85:

And the Underscore.js version:

the function that is passed as a second parameter to the filter function is the actual filter function, that mean that each object that will return true from that function will be added to the filtered collection – in our case each object that has a grade that is higher than 85 will be in the filtered array collection.

We could use some other function called countBy to get a similar (yet different) solution:

As you can see – complex logic can become really easy with the power of Underscore.js functions – and I showed only a few of the more simple ones. You can use complex operations like ‘map’ and ‘reduce’. Reduce function could be used for summing operations over objects, for example:

Let’s say that we have a collection of family, and each object in the family have an income. We want to calculate the total income of the family members. So, that’s easy with reduce:


That’s it! If you wonder what the third argument is then it is the initialization of the sum var – but it can be practically anything.

Underscore has a lot more functions to handle objects and object collections – you can find out all the function reference API on Underscore.js website.

Underscore.js have more features except from from the previous functionality, it has a built in templating function, a simple one, but that is where it is powerful – it is also simple to use…

All Underscore functions are chane-able,  that is another characteristic that was taken from jQuery.

Extending Underscore.js to your own use case:

It is very easy to extend Underscore.js and built on top of it – just use the mixin function to do that:

That example show a simple way to extend Underscore function base to your own, in this case we created a new function called capitalize which capitalize the first letter of the string and turning to lower case any other character.

Please note that in addition to all of the above Underscore also has a section on functions – this section can help you bind function and other helpful development workflow like ensuring a function could get called only once, delayed, run only after called X times and much more.

I want to end this post here, not because I don’t have anything else to add about Undescore functionality – it has a lot more power, that you can discover for yourself in the project website. I encourage you to do so! go ahead and play around