Posted By

timsommer on 08/03/12


javascript facade designpattern

Versions (?)

JavaScript Facade

 / Published in: JavaScript

When we put up a facade, we present an outward appearance to the world which may conceal a very different reality. This was the inspiration for the name behind the facade pattern. The facade pattern provides a convenient higher-level interface to a larger body of code, hiding its true underlying complexity. Think of it as simplifying the API being presented to other developers, something which almost always improves usability.

This is an unoptimized code example, but here we're utilizing a facade to simplify an interface for listening to events cross-browser. We do this by creating a common method that can be used in one’s code which does the task of checking for the existence of features so that it can provide a safe and cross-browser compatible solution.

  1. var addMyEvent = function( el,ev,fn ){
  2. if(el.addEventListener){
  3. el.addEventListener( ev,fn, false );
  4. }else if(el.attachEvent){
  5. el.attachEvent( 'on'+ ev, fn );
  6. } else{
  7. el['on' + ev] = fn;
  8. }
  9. };

Report this snippet  

You need to login to post a comment.