Writing modular java script

1,250 views

Published on

by Volodymyr Pavlyuk

Why do we need this?
Code reuse
Better maintainability
Better flexibility
Easier to test
Even big application doesn’t look very complex

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,250
On SlideShare
0
From Embeds
0
Number of Embeds
427
Actions
Shares
0
Downloads
7
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Writing modular java script

  1. 1. Writing Modular JavaScript by Volodymyr Pavlyuk October 2013
  2. 2. Why do we need this? • • • • • Code reuse Better maintainability Better flexibility Easier to test Even big application doesn’t look very complex
  3. 3. What is a Module?
  4. 4. Module is… ..an independent unit of functionality that is part of the total structure of a web application. Module consists of HTML + CSS + JavaScript.
  5. 5. Module vs. Widget • Widget doesn’t have business value, it’s dumb. • Module does.
  6. 6. {demo}
  7. 7. Modularity is not about singlepage applications or AMD…
  8. 8. … it’s all about loose coupling
  9. 9. Loose coupling • Reduce interfaces • Use mediator
  10. 10. Interface → Tight coupling
  11. 11. MessageBus Mediator Module Module Module Module
  12. 12. define('Mediator', function() { var eventsMap = []; var Mediator = function() {}; Mediator.prototype.on = function(ev, fn){ /* Add event listener to the map */ }; Mediator.prototype.fire = function(ev, payload){ /* Call listener */ }; return Mediator; });
  13. 13. define('foo', function() { function stopDropAndRoll() { /* Aaaa!! We all gonna die! */ } return { init: function (mediator) { mediator.on('Earthquake', stopDropAndRoll); } } });
  14. 14. define('bar', function() { return { init: function (mediator) { setTimeout(function() { mediator.fire('Earthquake'); }, 1000) } } });
  15. 15. require([‘Mediator', 'foo', 'bar'], function(Mediator, foo, bar) { foo.init(new Mediator()); bar.init(new Mediator()); });
  16. 16. Mediator • It provides consistency • It provides security • It provides communication
  17. 17. Module • Only call your own methods or those on the mediator • Don’t access DOM elements outside of your box • Don’t access non-native global objects • Anything else you need, ask the mediator • Don’t create global objects • Don’t directly reference other modules
  18. 18. What about JavaScript libraries? You are free to use any library or framework you want if loose coupling is preserved.
  19. 19. Does this work for really large applications? Yes.
  20. 20. Such pattern is very useful for embedding legacy code
  21. 21. define(‘uglyJQueryCode', function() { /* Legacy code */ return { init: function (mediator) { /* Facade */ } } });
  22. 22. Questions?

×