Sunday, March 30, 2014

Client side MVC with backbonejs - a simple example

Some developers do not pay much attention about the structure of the client side code in their web applications, and the way they organize the code may end up in a tangled pile of JavaScript codes which is less readable and difficult to maintain. Backbonejs is a framework for web front ends which solve these issue. You can build web applications with rich front ends with backbonjs and connects those all to your existing APIs over RESTful JSON interfaces.

In this post, I am trying to demonstrate how to build a client side MVC application with backbonejs, as simple as possible. The application is a list, which you can add and remove items. This is a very simplified version of the TodoMVC at, please proceed to the references at the end for more details.

Source code of this example : 

Application includes a model for individual list item, a collection to store list items, views/controllers to display, create, and delete items.

1. Index File

First we create an index file to hold all the html needed for the application, and inside this file we can load the libraries, basic application dependencies and application specific files.

<!doctype html>
<html lang="en" data-framework="backbonejs">
        <title>Backbonejs Simple MVC Example</title>

        <!-- The List -->
        <section id="list-section">
            <header id="header">
                <h1>The List</h1>
                <input id="new-item" placeholder="Type Here" autofocus>
            <section id="main">
                <ul id="items-list"></ul>

        <!-- The micro template for a single item -->
        <script type="text/template" id="item-template">
            <div class="view">
                <label><%- title %></label>
                <a href="#" class="destroy">X</a>

        <!-- Libraries -->
        <script src="lib/jquery.js"></script>
        <script src="lib/underscore.js"></script>
        <script src="lib/backbone.js"></script>
        <script src="lib/backbone.localStorage.js"></script>
        <!-- MVC -->
        <script src="js/models/item.js"></script>
        <script src="js/collections/list.js"></script>
        <script src="js/views/item-view.js"></script>
        <script src="js/views/list-view.js"></script>
        <script src="js/app.js"></script>

First section inside the body is the markups for the list which includes the heading, a text box to type list titles, and the empty list. When you type something in the text box and press enter the text should go to the list as an Item.

Next is the micro template for a single list item, in this application, template utility of underscorejs has been used to handle the templates. But you can use other JavaScript templating systems as well (Ex: handlebars).

Next section includes underscore frame work and other libraries (jQuery, underscorejs, and backbone local storage). Here, underscorejs is the only hard dependency of backbonejs.

Last section includes the application specific codes which we are going to discuss in the rest of this post.

2. Model (js/models/item.js)

/*global Backbone */
var app = app || {};

(function () {
 'use strict';

 app.Item = Backbone.Model.extend({

  // Default attributes
  defaults: {
   title: ''

This is the model for a single list item, with the only default attribute "title".

3. Collection (js/collections/list.js)

/*global Backbone */
var app = app || {};

(function () {
    'use strict';

    var List = Backbone.Collection.extend({

        // Reference to this collection's model
        model: app.Item,

        // Save all the items under the `"items"` namespace
        localStorage: new Backbone.LocalStorage('items-backbone'),

        // Next order number for new items
        nextOrder: function () {
            if (!this.length) {
                return 1;
            return this.last().get('order') + 1;

        // Items are sorted by their original insertion order
        comparator: function (item) {
            return item.get('order');

    // Create our global collection of **Items**.
    app.list = new List();

This collection groups the list items. Here we define the local storage namespace to store data, a function to get next order when creating a new item, and a comparator function to sort items.

4. List View (js/views/list-view.js)

var app = app || {};

(function ($) {
    'use strict';

    app.AppView = Backbone.View.extend({

        el: '#list-section',

        // Create New Items
        events: {
            'keypress #new-item': 'createOnEnter'

        // Bind to the relevant events at intialization 
        initialize: function () {

            this.$input = this.$('#new-item');
            this.$list = $('#items-list');

            this.listenTo(app.list, 'add', this.addOne);
            this.listenTo(app.list, 'reset', this.addAll);

            //{reset: true} - To suppresses 'add' events for intial loading  
            app.list.fetch({reset: true});

        render: function () {


        // Add a single list item
        addOne: function (item) {
            var view = new app.ItemView({ model: item });

        // Add all items in the list
        addAll: function () {
            app.list.each(this.addOne, this);

        // Get the list of attributes for a new item
        getAttributes: function () {
            return {
                title: this.$input.val().trim(),
                order: app.list.nextOrder()

        // Create a new item when pressing the enter key in text box
        createOnEnter: function (e) {

            if (e.which !== ENTER_KEY || !this.$input.val().trim()) {



In backbonejs, the view is the real controller, and the actual views are the html templates. Views, and templates together performs the job of controllers and views as in server side MVC application. There for, main application logic goes inside these views.

Most important thing to notice here is to how the view handles the events and listen to the changes of data and models. The function "createOnEnter" is called when the key down event occurs, and the view listens to the "add" event to update the list by calling "addOne" function when a new model(item) is added to the collection(list).

5. Item View (js/views/item-view.js)

var app = app || {};

(function ($) {
    'use strict';

    app.ItemView = Backbone.View.extend({

        // Tag name for the current view
        tagName:  'li',

        // Template for a single item
        template: _.template($('#item-template').html()),

        // Events specific to an item
        events: {
            'click .destroy': 'clear'

        // Listens for changes to item model
        initialize: function () {
            this.listenTo(this.model, 'destroy', this.remove);

        // Render the item
        render: function () {

            return this;

        // Remove the item from storage and UI
        clear: function () {

This is the view for a single list item. When rendering, it uses the micro template and the data from a model to render the new list item. When the click event occurs to delete an item, the "clear" function is called to remove the item from both UI and Storage.

6. App.js (js/app.js)

var app = app || {};
var ENTER_KEY = 13;
var ESC_KEY = 27;

$(function () {
    'use strict';

    new app.AppView();

Finally, the list view should be instantiated when the page is loaded. In addition to that, some global variables we need in the application have been defined here.

Please go through the references given below for leaning backbonejs in detail.

Developing Backbone.js Applications by Addy Osmani
Backbonejs TodoMVC

Sunday, December 15, 2013

How to create a simple Web Crawler

Web crawlers can be used for extracting information from web sites for many purposes. The simple example given here accepts an URL and exposes some functions to query the content of the page.

To check out the source code of this example :

These classes can be used (and improved/changed if necessary) in any web application. If you are doing any improvements, I recommend you to follow TDD and use the unit test class in the code.

Step 1 : Create the class, init function and required attributes 

In this example, xpath is used for querying the given web page. There is a one attribute to hold the page url, and another to hold the xpath object of the loaded page.

The init() function initializes the xpath object for the page URL assigned to url attribute.

class Crawler {

    public $url = false;
    protected $xpath = false;

    public function init() {

        $xmlDoc = new DOMDocument();
        $this->xpath = new DOMXPath(@$xmlDoc);
In the next two steps, you will add some simple functions to this class for querying data.

Step 2 : A method to query the content of tags   


This function returns an array of contents for the given tag name within the given limit (default limit is 10).
public function getInnerText($tag, $limit = 10) {        

    $content = Array();
    $searchNode = $this->xpath->query("(//{$tag})[position() <= {$limit}]");

    foreach ($searchNode as $node) {
        $content[] = $node->nodeValue;

    return $content;

Step 3 : A method to extract tag attributes (images, links etc.) 


This function returns an array of attributes for the give tag type on the page within the given limit (default limit is 10).

public function getTagAtrributes($tag, $attr, $limit = 10) {

    $attributes = Array();
    $searchNode = $this->xpath->query("(//{$tag})[position() <= {$limit}]");

    foreach ($searchNode as $node) {
        $attributes[] = $node->getAttribute($attr);

    return $attributes;

Step 4 : Usage 

Given below is the basic way of initializing and querying, please check the unit test class in the repository for more details.

$crawler = new Crawler();
$crawler->url = "crawlerTestVictim.html";

$images = $crawler->getTagAtrributes("img", "src");//Get the images
$headings = $crawler->getInnerText('h1');//Get the headings 
$links = $crawler->getTagAtrributes("a", "href");//Get the links

You can use two functions given above to write another function which crawls all the linked pages recursively by maintaining a queue of links.


Friday, May 24, 2013

How to create a simple Wordpress plugin

Last year, I was working on some projects related to bloging platforms such as Wordpress, and I became really passionate about Wordpress during that time. Wordpress has become a very popular CMS, although originally it came as a blog publishing platform. One of the main reasons for this popularity may be it's powerful plugin architecture. So, I thought it's better to write a simple tutorial about how to create a simple plugin for Wordpress.

In this tutorial, I am giving the main priority for the simplicity since I need to show how easy to create a plugin for Wordpress. I highly recommend to improve the structure of code if you are going to use this for a complex project.

This simple plugin will show, the head lines of the latest posts in the bottom of each single post page, so that users will be able to navigate to the latest articles without moving back to the home page.

To check out the source code for this example :

Step 1. Create the main plugin file

Create a directory (ex: wp_latest_posts) and create a php file as the main plugin file (ex: wp_latest_posts.php) and add the following header information in the top.

Plugin Name: LatestPosts
Plugin URI:
Description: Show the latest posts bottom of each single post page
Version: beta 1.0
Author: Author L.
Author URI:
License: GPL2
This is the standard plugin information which lets Wordpress identify your plugin.

Step 2. The function to get latest posts

Add the function given below to the file created in the step 1 after the header information. On execution, it will return a brief list of last five posts ordered descending by post date so that the latest one to be in the top. I guess the code is self explanatory.

function get_latest_posts_list() {

    $args = array(
        'posts_per_page' => 5,
        'numberposts' => 5,
        'offset' => 0,
        'category' => '',
        'orderby' => 'post_date',
        'order' => 'DESC',
        'include' => '',
        'exclude' => '',
        'meta_key' => '',
        'meta_value' => '',
        'post_type' => 'post',
        'post_mime_type' => '',
        'post_parent' => '',
        'post_status' => 'publish',
        'suppress_filters' => true );

        $posts = get_posts( $args );

    if (empty($posts) || count($posts)<1) return;

    $html = "<ul>";
    foreach ($posts as $post) {

    $html .= "<li><a href='".$post->guid."'>".
        "</a> - ".strip_tags(substr($post->post_content, 0, 150)).
    $html .= "</ul>";

    $container = "<div><h2>Latest Posts... </h2>{$html}</div>";

    return $container;

Step 3. Create the filter function

Wordpress uses filter functions to pass data through. So, here we can use a filter function to add the list retuned by the function in step 2 to the bottom of each post. Add this function too to the main file after the function created in the step 2.

function show_latest_posts($content){

        return $content . get_latest_posts_list();
    } else{
        //if `the_content` belongs to a page no change to `the_content`
        return $content;

Next, this filter function should be added to the hook. Add the line given below to the main file after the filter function.

add_filter('the_content', 'show_latest_posts');

Now, our simple plugin is ready to install and test.  

Step 4: Installation

Please follow the instructions given below to install the plugin.

  • Upload the 'wp_latest_posts' folder (created in the step one which contains the plugin main file) to the `/wp-content/plugins/` directory
  • Activate the plugin through the 'Plugins' menu in WordPress
  • Compress 'wp_latest_posts' folder as a zip file. (
  • Login as wp admin.
  • Go to "Plugins --> Add New"
  • Click Upload
  • Brows and select the file(, click "Install Now" button.
  • Activate the plugin

Now open a post in your blog (you should have at least 2 posts in your blog) and check the bottom of the page between the post and comments areas.

Above code was tested in WordPress 3.3.1.


Saturday, September 29, 2012

JavaScript The Good Parts - To see the real beauty of the language


 Recently, I finished reading the book "JavaScript The Good Parts" written by Douglas Crockford. Actually, many developers, although they have used JavaScript for many years, they haven't tried to learn it in a proper way. Therefore there is a great amount of poorly written codes in the world wide web. And also JavaScript said to be the world's most misunderstood programming language. So, this is a great book to read for any one who wants to see the real beauty of JavaScript.

The book has ten chapters and five appendixes which describes the good and bad parts of the language, and how to manipulate the good parts, and how to avoid the bad parts. I did read the book from the first page to the last page and found there is nothing to ignore or skip without reading. And my passion about JavaScript was increased exponentially because of this book, since I found there are many workarounds to overcome the limitations of the language.

After all, in any language there may be many bad features, but a cleaver programmer should know how to manipulate the good parts and avoid the bad parts with better programming practices, to solve the problems. 

For more information:

Saturday, September 8, 2012

Javascript Module Pattern

Module pattern is one of the well know design patterns in JavaScript. I did read about this pattern, for the first time, in a publication done by Douglas Crockford. Since then, I have used this pattern in many occasions in my coding.

Using a module, an interface can be presented, by hiding the implementation and the state of an object. And it's a way of having private attributes and methods. A simple implementation is given below.

var containers = (function () {

        var module = {};
        var default_container_width = 500; //private property

        var possible_containers_list = new Array();

        module.list = possible_containers_list; //public property

        function getContainerWidth() {//private function
            // ...

        module.hideAll = function () {//public function
           // ...

        return module ;

To call the public functions and to get the public property values:

var list = containers.list;

With this pattern, the use of global variables can also be reduced.

Sunday, July 15, 2012

De Morgan's Laws in Programming

Recently, while I was reviewing some codes, I saw there were some conditional statements that check for the same condition but written in different ways. Most of these statements were written with common sense without using any mathematical analysis, since those are too simple to go for a more formal approach. The two identical conditional statements that has been written in different ways are given below.


if ($comment['deleted'] == '1' || $comment['approved'] == '0') {
} else {


if ($comment['deleted'] == '0' && $comment['approved'] == '1') {
} else {

Obviously, the above lines say that the inverse of the first condition is equals to the second condition and vice versa. That is...

 ($comment['deleted'] == '1' || $comment['approved'] == '0')  "equals to" !($comment['deleted'] == '0' && $comment['approved'] == '1') .

That means simply in this case...

(true || false) ==> !(false && true)

This is an one real life example to prove the theory called "De Morgan's Law" in Pure Mathematics. Theories like these can be used to improve the source codes in many ways. In the cases like above, one can write more consistent and efficient codes with the knowledge of these theories.

On the other hand, in the early ages, if the students are aware of the real applications of those theories they will learn those with some more enthusiasm.

More details:'s_law


Saturday, March 24, 2012

How to work around the limitations set by Same Origin Policy...

Last week, I wanted to make some Ajax requests from a page generated by some web application to another web application. These two applications are hosted in two different servers, with different domains. To do this type of a thing, you can't use a normal method because of the limitations set in place by "Same Origin Policy".

Same Origin Policy is a security concept for client side programing languages. This policy prevents the client side scripts accessing the pages from different web sites. For an example, if your application is hosted in the "hostA" and a client side script of your application wants to send an Ajax request to a another application that is hosted in "hostB", then this request will be prevented by the Same Origin Policy. To be able to make that type of a request, both host and protocol should be same, according to the Same Origin Policy.

For more details :

There are few methods listed below to work around this limitation. 
  • With html5 there is a method formalized for this, but it supports only in the newest browsers. 
  • Cross Origin Resource Sharing (CORS) : This is a way of enabling open access between cross domains by making the server to be accessed by the pages of other servers. This is an excellent guide for this method:
  • JSONP : This provides a method for requesting data from a different server with a different domain. For more details:  
When I was researching about these, I found an extremely cool JavaScript library called "easyXDM", which is developed by combining above methods. I highly recommend that library for anyone that wants some work around for the cross domain requests.

More details: