Posted By

timsommer on 07/31/12


Tagged

javascript command html designpattern


Versions (?)

JavaScript Command Pattern


 / Published in: JavaScript
 

The Command pattern aims to encapsulate method invocation, requests or operations into a single object and gives you the ability to both parameterize and pass method calls around that can be executed at your discretion. In addition, it enables you to decouple objects invoking the action from the objects which implement them, giving you a greater degree of overall flexibility in swapping out concrete 'classes'.

  1. (function(){
  2.  
  3. var CarManager = {
  4.  
  5. // request information
  6. requestInfo: function( model, id ){
  7. return 'The information for ' + model +
  8. ' with ID ' + id + ' is foobar';
  9. },
  10.  
  11. // purchase the car
  12. buyVehicle: function( model, id ){
  13. return 'You have successfully purchased Item '
  14. + id + ', a ' + model;
  15. },
  16.  
  17. // arrange a viewing
  18. arrangeViewing: function( model, id ){
  19. return 'You have successfully booked a viewing of '
  20. + model + ' ( ' + id + ' ) ';
  21. }
  22.  
  23. };
  24.  
  25. })();
  26.  
  27. CarManager.execute = function (name) {
  28. return CarManager[name] && CarManager[name].apply(CarManager, [].slice.call(arguments, 1));
  29. };
  30.  
  31. /*** Usage ***/
  32. CarManager.execute("arrangeViewing", "Ferrari", "14523");
  33. CarManager.execute("requestInfo", "Ford Mondeo", "54323");
  34. CarManager.execute("requestInfo", "Ford Escort", "34232");
  35. CarManager.execute("buyVehicle", "Ford Escort", "34232");

Report this snippet  

You need to login to post a comment.