Showing posts from September, 2012

Pushing Ajax responses using Observer Pattern in JavaScript

Last week I'd played around with couple of design patterns in JavaScript (Constructor and Module pattern). I really liked the Module pattern i.e. the approach taken in JavaScript to enable encapsulation of data in a Class (functions in JavaScript). I was building an application using these Design patterns but found that making Ajax request inside a function in a module was not the right approach. JavaScript would send a request and start executing the next statement. I wanted to use an approach that would push the data from the Model whenever there was some new data available. This lead me to try the 'Observer pattern' in JavaScript.

Module Pattern in JavaScript

Couple of days back I wrote about the Constructor Pattern in JavaScript wherein I explained how classes can be simulated using functions in JavaScript. Also, on how the prototype property can be used to extend another class. The other important element in any of the Object-Oriented programming language is the concept of encapsulation i.e. providing private members that can be accessed only by the members of the same class. I came across the Module Pattern today and found that it is quite easy to achieve encapsulation in JavaScript. Though the variables in JavaScript can't be declared as private or public, but closures can be used to emulate encapsulation.

Constructor Pattern in JavaScript

Over the last few weeks I've been learning Object-Oriented concepts in JavaScript and have been building applications on top of it. I've an understanding of Object-Oriented concepts in many of the Server side programming languages and was trying to draw parallel lines with JavaScript. As it turns out, JavaScript is a class-less language but the concept of classes can be simulated using functions. In JavaScript, functions are not primitive types but are special kind of objects and hence you can set properties on them and can also invoke methods on them.