Posted by & filed under JavaScript, web developing.

Download the source

You can download, and check the source from my github account

A lot of beginning javascript developers might find it hard to start with design patterns. And for most projects larger frameworks, for example backbone.js would be overkill. I created a very simple todo example application based on mvc. I tried to keep the app as clean and concise as possible. Therefore the application is “ugly”, no styling no images etc. I did use jQuery for event dispatching, to my opinion this easier to understand and to maintain than pure javascript events.

Application structure

The application has three main classes and i did not follow the mvc pattern really strictly, for example i could have implemented the model more strictly, with getters an setters, and for example use a singleton for for the model. I did however decoupled the model from the view by the controller.

The Model

The model module is essentially one private array which stores the todo items and is exposed by some public methods.

var Model = function () {
        var _todos = new Array();    

	var notifyController = function () {	
            $('body').trigger('updateView');
	}
        // public methods
	return  {
		addTodo: function ( todo ) {
                    _todos.push(todo);
                   notifyController();
		},
                editTodo: function( index, newTodo ){
                    _todos[index] = newTodo;
                },
                deleteTodo: function ( index ) {
                   _todos.splice(index,1);
                   notifyController();
		},
                getData: function(){
                    return _todos;
                }
	};
};

The View

the view module below handles the user events and updates the view (html file). The view is coupled with the html file. The main events are the “add-event”, triggered by the “add” link and the enter key, and the delete event which the “delete” link triggers.

var View = function () {
	var updateView = function ( todos ) {	
            $('#todoList li').remove();
            for( var i = 0, len = todos.length; i < len; i++ ){
              $('#todoList')
               .append( '<li>' + todos[i] 
               + '<a data-index="' + i + '" href="#">remove</a></li>');
            }
	};
        
        //set the handlers for the view
        var initView = function(){
            //add
            $("#addTodoButton").on("click", function(){
                var event = jQuery.Event("addItem");
                event.todo = $('#addTodo')[0].value;
                $('body').trigger(event);
                $('#addTodo')[0].value = '';
            });
            // track enter key
            $('#addTodo').on("keypress", function(e){
              if(e.which == 13){
                var event = jQuery.Event("addItem");
                event.todo = $('#addTodo')[0].value;
                $('body').trigger(event);
                $('#addTodo')[0].value = '';
               }
              });

            //delete
            $('#todoList a').live("click", function(e){
                var $todo = e.currentTarget;
                var event = jQuery.Event("deleteItem");
                event.index = $($todo).attr('data-index');
                $('body').trigger(event);
            });
        };
        initView();
        
	return  {
		updateView: function (todos) {
                    updateView(todos);
		}
	};
};

The Controller

The controller module listens for the events disposed by the view module, the controller is aware of the model and the view.

var Controller = function (view, model) {
        var _view = view;
        var _model = model;

        // event binding
        $('body').bind('addItem', function(e) {
           _model.addTodo( e.todo );
        });
         $('body').bind('deleteItem', function(e) {
           _model.deleteTodo( e.index );
        });
        $('body').bind('updateView', function(e) {
            _view.updateView( _model.getData() );
        });
};

The Application

The last script is the simple initialize script which binds the MVC modules together. The model and the view are instantiated and passed to the controller.

//init
var model = Model();
var view = View();
var controller = Controller(view, model);

The current application is very simple. If the app would be extended I would start by creating a “todo” view item, this would separate the single todo item from the listing ( and perhaps sorting ) of the todo items. Extending applications like this maintain a clear separation of functions, which definitely helps if an applications grows larger.

Download the source

You can download, and check the source from my github account

Posted by & filed under books, web developing.

Book cover of The tangled web
  • Author: Michal Zalewski
  • publisher: O’Reilly Media ( No Starch Press )
  • pages: 273

Introduction

I liked the book, the book is thorough, on a tough subject. What I missed is a more practical approach of the secure web, almost all web developers are also intrigued by hackers. to my opinion hacking itself could make developers understanding the holes of the web more easily. I really would liked some more practical examples of websites and how to brake them.

The book is handy for reference ( although the internet is might be more useful ). I expected to learn some fundamentals to cope with security issues in the daily live of webdeveloping, that after reading the book and messing around with some code examples my awareness for possible security flaws would be raised.

Security Awareness

The untangled web partially raised my awareness. Since i read the book i am more aware of the possibility of security issues in many layers of the web, plugins, java applets and other stuff that lives on the internet. Again what I missed was a more practical approach. For example the book could start with a simple php site implementation. This should be of no concern for the average reader of this book. With the example site created the book could have show ways how to hack the site. I know this might not be the most ethical methodology, but for me it would be the best way to remember all the information about security issues and how to prevent them.

The Future

Later chapters describe some modern features of the web. Luckily most of the these are reasonably robust, for example web sockets and web workers. In this section the book becomes also more practical and more fun to read. I enjoyed the epilogue of the book where the analogy is made between the society en the online society which hasn’t had any time yet to form human-based ethics. Regarding piracy and security.

Conclusion

There is a lot to be said about web security, much more than i would have known. I hope i have raised my own awareness regarding security to implement it in my daily job. However i will have a hard time selling the extra time in advance to clients.

I must compliment the author for writing this reference book about security issues on the internet. It is easy to see that a lot of research has gone into this book. Bottom line this isn’t a fun developing book but it will certainly improve your quality as a developer.

The books product page

Posted by & filed under books, JavaScript.

Book cover of Javacript Web Applications
  • Author: Alex MacCaw
  • publisher: O’Reilly Media
  • pages: 280

Introduction

A book to create javascript applications for the intermediate javascript developer. This book gives you a kickstart, helps you choose the right framework, and architectural choices for your application

Review

The book has a fast pace, no thoroughly introduction of MVC, I think this is justified. MVC has been explained a lot of times the last decade. The author of this book explains a lot of modern frameworks en modern technologies

This book is not for the novice javscript developers even the intermediate developers can have a hard task grasping the contents of this book. You need to understand the core of javascript and jQuery as well as design patterns, at least a couple of them to get the most out of this book.

Personally for me the topic of this book is a bit overkill for the web applications I develop. Hence if the scale of my webapps grows more complex I will definitely turn to this book. It will explain a lot of usefull state of the art Javascript MVC frameworks.

After explaining several ways of working with events in javascript application the author starts digging into MVC. First a chapter on Models and ORM (Object-relational mapping) and how to populate your model with external data. Offline as well as online storage of the model is also described in this chapter. The next chapter is about the controller, the best ways of event delegation and accessing the views. And finally the views itself, with modern js templating techniques. After the MVC foundation Spine.js and Backbone.js are introduced and explained. Two of the most known patterns for small ( spine.js ) to large ( Backbone.js ) web applications.

I also liked to addional information on modern topics like LESS ans CSS 3 and NodeJS. For me this was pure complementary information, and I had rather seen some more introduction in the beginning.

Bottom line

JavaScript Web Application is a must have book to plan and develop larger applications. It tells you everything you need to know to structure a application, but I think it would help to read other book before this book to get the most out of it, for example Javascript Patterns. The books product page

Posted by & filed under JavaScript.

For a couple of months I was intrigued by node.js, but i couldn’t find any simple guides to start with node on windows. It turns out it is actually very simple to start learning node.js on windows. To start you need 4 things.

  1. The windows node server, nodejs.exe download at http://nodejs.org
  2. A hello world node script ( example.js )
  3. A command promt, set at the same locations as the script en node server
  4. And of course a browser

Hello World script

Save the script below as example.js in the same directory as the downloaded node.exe file.

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.end('<h1>Hello Nodejs</h1>');
}).listen(1337, "127.0.0.1");
console.log('Server running at http://127.0.0.1:1337/');

Start your first node script

Now all you need to do are the following steps.

  1. Start node.exe
  2. execute the script with the command prompt: node example.js
  3. browse to the node server wich is running at: http://127.0.0.1:1337/

Your screen should be comparable to the screenshot below

a screenshot of the node.js setup

I hope this was as easy for you as it was for me. For now I hope to wire some more intersting blog posts about Node on Windows, for example Node on IIS, but in the next post I will explore node.js a bit deeper

Posted by & filed under books, JavaScript.

Book cover of Supercharged JavaScript Graphics
  • Author: Raffaele Cecco
  • publisher: O’Reilly Media
  • pages: 280

Introduction

A pleasant book written by an author with lots of experience. The examples are fun, and realistic. The tempo of the book is easy to follow for intermediate JavaScript developers.

Review

I like that the book begins with a DHTML example, this makes the reader really understand the fact that building the web is possible with many tools and that each tool has its cons and pros. The newest toys ( canvas, webgl etc ) aren’t necessarily the best or the fastest to build a proper user experience. In the beginning of the book the reader get acquainted with; the browser landscape, sprites, framerates and best practices for working with the DOM which is a pain for performance. The code examples are clear and luckily without excessive comments, which makes the example easy to read for the more experienced developers which are books target group.

The next chapters concern page enhancing techniques like scrolling effects, ui-libraries and shows the best way to create user interface elements form scratch. Al these chapters are a fine introduction for the more performance hungry subjects of games.

The second part of the book dicusses games, staring with a DHTML version of space invaders. This game example incorporates a lot previeous learned techniques en demonstrates the power and performance of well used DHTML.

Of course the power of the newer toys are easy to see with the examples in the book for example the ( recursive ) tree example is a brilliant example of the performance of the canvas element. The bigger part of this book emphasizes on the canvas element. The book clearly demonstrates the posibillities and raw power of the element.

The following chapters cover mobile javascript graphics, phonegap and the Google Charts API.
At first the mix of topics seemed strange to me, however the chapter were really fun to read and I will definitilly use Google Charts in upcoming projects if needed. jQuery Mobile is equally interesting, though personally I would probably take a more responsive way in the future with embedding the touch events into a global library for websites.

Bottom line

this book definitely is a fun read supported by excellent examples for medior to advanced javascript developers who develop applications at his moment, the author makes use of contemporary, but proven libraries and API’s . Which is a plus these days with swift innovation cycles.

The books product page