Flash Player 9 (or above) is needed to view presentations.
We have detected that you do not have it on your computer. To install it, go here.

Like this presentation? Why not share!

Javascript Design Patterns



A brief introduction about Javascript design patterns

A brief introduction about Javascript design patterns



Total Views
Views on SlideShare
Embed Views



8 Embeds 1,645

http://hop2croft.wordpress.com 1637
https://www.linkedin.com 2
http://translate.googleusercontent.com 1
http://clothdiaperblog.com 1
http://testerinyou.blogspot.com 1
http://showtime-cy.blogspot.com 1
http://www.linkedin.com 1
https://hop2croft.wordpress.com 1


Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

CC Attribution-NonCommercial-ShareAlike LicenseCC Attribution-NonCommercial-ShareAlike LicenseCC Attribution-NonCommercial-ShareAlike License

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
Post Comment
Edit your comment

Javascript Design Patterns Javascript Design Patterns Presentation Transcript

  • PRESENTATION SCOPE• Background.• What is a Design Pattern?.• Structure of a Design Pattern.• Anti-patterns.• Design Patterns in Javascript.• MV* Patterns.
  • BACKGROUND 1995 Design Patterns: Elements Of Reusable1977 First mention of Object-Oriented patterns in Software by Erich engineering in A Gamma, Richard Helm,Pattern Language by Ralph Johnson and Christopher John Vlissides so called Alexander. GoF 1987 First studies about applying patterns to programming. Presented at the OOPSLA conference by Kent Beck and Ward Cunningham
  • BACKGROUND• 2002 Patterns of Enterprise Application Architecture by Martin Fowler• 2003 Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions by Gregor Hohpe and Bobby Woolf• 2009 SOA Design Patterns by Thomas Erl
  • WHAT IS A DESIGN PATTERN?1. A pattern is a general reusable solution to a commonly occurring problem within a given context.2. It is a description or template for how to solve a problem that can be used in many different situation REMEMBER …A design pattern is not a finished design that can betransformed directly into code
  • WHAT IS A DESIGN PATTERN? 1. Patterns are proven solutions. Solid approaches to solving issues in software development. 2. Patterns can be easily reused. Less time about your code structure, more time about solution logic 3. Patterns can be expressive. Set structure and ‘vocabulary’ to the solution presented. Communication is easier.
  • STRUCTURE OF A DESIGN PATTERN • Pattern name and a description • Context outline • Problem statement. • Solution. • Design. • Implementation. • Illustrations. • Examples. • Co-requisites. • Relations. • Known usage. • Discussions.
  • ANTI-PATTERNS Term coined in 1995 by Andrew Koening in the C++ Report. • Describe a bad solution to a particular problem which resulted in a bad situation occurring • Describe how to get out of said situation and how to go from there to a good solutionThe build Monkey Antipattern
  • DESIGN PATTERNS (IN JAVASCRIPT)• Creational. How the entities should be created to fit its purpose. Constructor, Factory, Abstract, Prototype, Singleton and Builder.• Structural. Simple ways of relationship between different objects. Module, Decorator, Facade, Flyweight, Adapter and Proxy• Behavioral. improving or streamlining the communication between disparate objects in a system. Iterator, Mediator, Observer, Command and Visitor.
  • CONSTRUCTOR AND PROTOTYPEPATTERN.Keep in mind that Javascript is a class-less programming language, but thesecan be simulated usign functions. function Car ( model,color,year ){ this.model = model; this.color = silver; this.year = 2012; this.getInfo = function(){ return this.model + + this.year; } }Constructor Pattern. Create new Car objects. var civic = new Car( "Honda Civic" , "blue", 20000 );Prototype Pattern. Functions in javascript have a property called a prototype. Car.prototype.toString = function(){ return this.model + ” did " + this.miles + " miles"; };
  • MODULE PATTERN.Group several related elements such as classes, singletons,methods, globally used, into a simple object. It fakes classes inJavascript.Defined Richard Cornford in 2003 and popularized by DouglasCrockford in his lectures.Pros:• Encapsulation, it gives us an API (public and private attributes or methods),• Avoid names conflicting with other function• Easier debugging (public functions are named)Cons:• Difficult to refactor.
  • MODULE PATTERN.var testModule = (function(){ var counter = 0; var privateMethod = function() { // do some very nasty stuff. } return { incrementCounter: function() { return counter++; }, resetCounter: function() { console.log(counter value before reset:’+ counter); counter = 0; } }; })();
  • REVEALING MODULE PATTERN.Coined by by Christian Heilmann (Mozilla Foundation).Pros:• Sintax more consistent and easy to read.• Easier to refactor. var myRevealingModule = (function(){ var name = John Smith; function updatePerson(){ name = John Smith Updated; } function setPerson (value) { name = value; } return { set: setPerson, }; }());
  • OBSERVER OR PUB/SUB PATTERN.• It is a design pattern which allows an object (known as a subscriber) to watch another object (the publisher).• Loose coupling, ability to break down our applications into smaller, general manageability.• Many implementation in Javascript. • Ben Almans Pub/Sub gist https://gist.github.com/661855 (recommended) • Rick Waldrons jQuery-core style take on the above https://gist.github.com/705311 • Peter Higgins plugin http://github.com/phiggins42/bloody- jquery-plugins/blob/master/pubsub.js. • AppendTos Pub/Sub in AmplifyJS http://amplifyjs.com • Ben Truymans gist https://gist.github.com/826794
  • OBSERVER OR PUB/SUB PATTERN.var pubsub = {}; (function(q) { var topics = {}, subUid = -1; q.publish = function( topic, args ) { if ( !topics[topic] ) { return false; } var subscribers = topics[topic], len = subscribers ? subscribers.length : 0; while (len--) { subscribers[len].func(topic, args);} return this; }; q.subscribe = function( topic, func ) { if (!topics[topic]) { topics[topic] = []; } var token = (++subUid).toString(); topics[topic].push({ token: token, func: func }); return token; }; }( pubsub ));
  • COMMAND PATTERNThe Command pattern aims to encapsulate method invocation, requestsor operations into a single object and gives you the ability to bothparameterize and pass method calls around that can be executed at yourdiscretion.(function(){ var CarManager = { buyVehicle: function( model, id ){ return You have purchased Item + id + , a + model; }}; })(); CarManager.execute = function (name) { return CarManager[name] && CarManager[name].apply (CarManager, [].slice.call(arguments, 1)); }; CarManager.execute("buyVehicle", "Ford Escort", "34232");
  • MV* PATTERNS• Software Design pattern or Architecture design pattern?.• Coined by Trygve Reenskaug during his time working on Smalltalk-80 (1979) where it was initially called Model-View- Controller-Editor.• Variations: • MVC. Model-View-Controller. Spine.js / Backbone.js (MVR) • MVP. Model-View-Presenter. Backbone.js • MVVM. Model-View-ViewModel. Knockout.js / Knockback.js• It has been structuring desktop and server-side applications, but its only been in recent years that come to being applied to JavaScript. • http://addyosmani.github.com/todomvc/
  • BACKBONE.JS MVC, MVP OR MVR?• Flexible framework to build Javascript web applications.• Backbone.js doesn’t fit in any specific pattern.• There is no controller in Backbone. Views and Routers instead.• Backbone’s Architecture. • Model. Extend from Model or Collection. var Todo = Backbone.Model.extend({ defaults: { content: "empty todo...", done: false }, // Ensure that each todo created has `content`. initialize: function() { if (!this.get("content")) { this.set({"content": this.defaults.content}); } } });
  • BACKBONE.JS COLLECTIONS• Model. Extend from Collection. var User = Backbone.Collection.extend({ model: User, url: https://api.twitter.com/1/user/show.json?id=7&callback=?, parse: function(response) { //console.log(parsing user ...); return response; } });
  • BACKBONE.JS VIEW• View. It can see as a a View, a Presenter or even a Controller.var PageView = Backbone.View.extend({ el: $(body), events: { click button#add: doSearch }, initialize: function() { this.template = _.template(<li><%= name %></li>); _.bindAll(this, render, addItem); this.(reset, function(collection) { _this.$(#tweets).empty(); collection.each(function(tweet) { _this.addItem(tweet); }); }); this.render(); }, …
  • BACKBONE.JS VIEW CONT.…doSearch: function() { var subject = $(#search).val() || Node.js; this.tweets.url = http://search.twitter.com/ search.json?q=’+ subject + &rpp=8&callback=?; this.tweets.fetch(); }, render: function() { var html = template({ img: item.get(profile_image_url) , user: item.get(from_user_name), text: item.get(text) }); $(#tweets, this.el).append(html); return this; }});You also use templating within the View layer. (Mustache.js, Jquery.tmpl, ….).
  • BACKBONE.JS ROUTER• Router. It may be seen as a pseudo-controller.var myRouter = Backbone.Router.extend({ routes: { "help": "help", // #help "search/:query": "search", // #search/users "search/:query/p:page": "search" // #search/users/p7 }, help: function() { ... }, search: function(query, page) { ... }});
  • SPINE.JS. MVC LIBRARY.• Controllers are considered the glue between the Model and the View.var PhotosController = Spine.Controller.sub({ init: function(){ this.item.bind("update", this.proxy(this.render)); this.item.bind("destroy", this.proxy(this.remove)); }, render: function(){ this.replace($("#photoTemplate").tmpl(this.item)); return this; }, remove: function(){ this.el.remove(); this.release(); }});
  • KNOCKOUT.JS MVVM• Defined in 2005 by John Grossman for use with Windows Presentation Foundation (WPF) and Silverlight• More clearly separate the development of user- interfaces (UI) from that of the business logic and behavior in an application.• Make use of declarative data bindings to allow a separation of work on Views from other layers. It provides data-binding from the Model directly from the View• Based on Model View PresentationModel. Martin Fowler wrote an article on PresentationModels back in 2004
  • KNOCKOUT.JS MVVM• Model. It uses the Observable property that can notify subscribers about changes and automatically detect dependencies• View. A KnockoutJS View is simply a HTML document with declarative bindings to link it to the ViewModel• ViewModel. The ViewModel can be considered a specialized Controller that acts as a data converter. It changes Model information into View information, passing commands from the View to the Model.
  • KNOCKOUT.JS VIEWMODELfunction AppViewModel() { this.firstName = ko.observable("Bert"); this.lastName = ko.observable("Bertington"); this.fullName = ko.computed(function() { return this.firstName() + " " + this.lastName(); }, this); this.capitalizeLastName = function() { var currentVal = this.lastName(); this.lastName(currentVal.toUpperCase()); };}// Activates knockout.jsko.applyBindings(new AppViewModel());
  • KNOCKOUT.JS VIEW• Plain HTML<p>First name: <strong data-bind="text: firstName"></strong></p><p>Last name: <strong data-bind="text: lastName"></strong></p><p>First name: <input data-bind="value: firstName" /></p><p>Last name: <input data-bind="value: lastName" /></p><p>Full name: <strong data-bind="text: fullName"></strong></p><button data-bind="click: capitalizeLastName">Go caps</button>