Your SlideShare is downloading. ×
0
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Enterprise js pratices
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Enterprise js pratices

1,147

Published on

Word-Two …

Word-Two
JavaScript mistakes from the C# programmer
Solution structure
Solution architecture
Dependency management
Product module
UI Components
Event Driven Messaging
Application routing
Localization
Logging

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

No Downloads
Views
Total Views
1,147
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
18
Comments
0
Likes
1
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. Enterprise JSPracticesREFERENCE ARCHITECTURE
  • 2. Marjan NikolovskiA professional senior software engineer andconference speaker who is mainly hooked on the.NET platform as development platform and itsderivatives, but from time to time knows to kill sometime with open source software.Usually spends his time writing systems backendand testing cutting edge technologies.In spare time actively participating in holdingtechnical presentations on conferences andresearching. Specially interested in Distributedprogramming, Software architecture, Middleware,SOA, Non-relational databases and Workflowdriven systems.
  • 3. Agenda  Word-Two;  JavaScript mistakes from the C# programmer  Solution structure;  Solution architecture;  Dependency management;  Product modules;  UI Components;  Event Driven Messaging;  Application routing;  Localization;  Logging
  • 4. Word-Two  Enterprise JavaScript app - heavy data app that is hard to be maintained;  Development time increase as the complexity and the codebase grows up;  Frontend development usually not taken seriously;  Frontend development always underestimated and without certain development plan and architecture;
  • 5. JavaScript mistakes from the C#programmer  Writing jQuery still requires knowledge of JavaScript;  Using global variables and functions;  Object literal;  Self-Executing Anonymous Function;  Revealing Module Pattern;  Array and object declaration gone bad;  False value understanding;  Default value testing;  Using wrong comparison operators;  Misusing For..in statement on Arrays;  Misusing For..in statement on Objects;  Function and Object Scope in JavaScript;  Not aware of JSLint;
  • 6. Using global variables andfunctions var invalid_username = "Username exists"; function log_in() { //Placed in global scope when executed invalid_username = "Really Bad"; } //Bad way to prevent namespace clashing function namespace_log_out() { } //Functions window.log_in(); window.namespace_log_out(); //Global variables are available off window object console.log(window.invalid_username); console.log(window.log_in); console.log(window.namespace_log_out);
  • 7. Object literal  Similar to JSON syntax; //Object Literal declaring properties and methods  Provide properties and function by choise; var user_model = {  Everything defined in the object literal is public; //public property username: "Some user", //public method login: function() {} }; Pros Cons Remove global namespaces to properties, Difficult to maintain and understand variables and methods Functionality can be added at a later No way to have private properties and/or point methods All properties and methods are public
  • 8. Self-Executing Anonymous Function  Non name function that executes after it is defined;  Isolate variables and functions from global namespace; //Self-Executing Anonymous Function: (function() { Pros Cons //private variable Hide implementation All information is var username = "Some username"; from external code hidden //private function The code runs only Complicated on first function login() {} once sight Not using object literal login(); notation }());
  • 9. Revealing Module Pattern  Uses the concept of the Self-Executing Anonymous Function;  Store the result into a variable; //Revealing Module Pattern (Public & Private) var user_proxy = (function() { var me = {}, Pros Cons //Private property username = "Some username"; Allow private and //Public property me.message = "A message"; public properties and //Public method methods me.Login = function() { pvtLogin(); Easy to understand }; //Private method function pvtLogin() { //Do something... } //Return just the public parts return me; }());
  • 10. Array and object declaration gonebad  Many ways to create an object, but only one is the correct one;  Hesitate the temptation to use the new keyword; // bad practice // bad practice var user = new Object(); function User(uname){ this.username = uname; // good practice } var user = {}; var user = new User(‘test’); User.username == ‘test’ var user = User(‘test’); user.username != ‘test’ user.username == window. username
  • 11. False value understanding  Same goes for arrays. Many ways to create an array, but only one is the correct one; // bad practice var userList = new Array(10); userList[0] === undefined; userList.length == 10; // good practice var userList = [];
  • 12. Default value testingC# JavaScriptIf(user != null && user.Length > 0) If(user){ { // do something // do something} } OR user = user || ‘default value’;
  • 13. Using wrong comparison operators  JavaScript ninja behavior can sometimes gives us unexpected results;  Sometime value comparison is not what it looks like;  Always use === or !== when doing comparison in JavaScript; // Unexpected comparisons 0 === //false 0 == ‘ //true 0 === 0 //false 0 == ‘0’ //true false === 0 //false false == 0‘ //true null === undefined //false null == undefined //true trn === 0 //false trn == 0 //true
  • 14. Misusing For..in statement on Arrays  Does not guarantee the order of the items that are going to be retrieved by the iterator;  The iterator can iterate both array and objects;  Bad declaration can result in incorrect iterator execution; var user = { var userArray = []; username: ‘Test’, userArray.push(‘data’) name:’Some name’ userArray.name = ‘Test’; }; for(var data in user){ for(var data in user){ alert(data); alert(data); alert(user[data]); } } // outputs username, name // outputs 0, name // outputs data, Test
  • 15. Misusing For..in statement onObjects  In most cases For..in is not harmful when iterating objects;  The problem arise when we inherit properties from the prototype;  Always check if the property exists in the instance before accessing it; var User = function(uname){ var User = function(uname){ this. Username = uname; this. Username = uname; return this; return this; } } User.prototype = { User.prototype = { isDeleted:true isDeleted:true } } var usr = new User(‘Test’); for (var name in username ) { for (var prop in User()) { if (username.hasOwnProperty(name) ) { // outputs Username // outputs Username // outputs isDeleted } } }
  • 16. Function and Object Scope inJavaScript function login() {  Variable scope visible in the var user = "test", function; isWrongCaptcha = true; if (isWrongCaptcha) {  All internal closures or var timeToWait = 10; console.log( "Waiting " + timeToWait + " minutes" ); functions will see the defined internal_log_in(); variables in the parent } function scope; function internal_log_in() { //The chew function also has access to the //timeToWait variable because it is part of the //eat functions scope console.log("After waiting " + timeToWait + " minutes, " + "I am going to login to the system"); } } login(); //Waiting 10 minutes //After waiting 10 minutes, I am going to login to the system
  • 17. Not aware of JSLint  JSLint is a static code analysis tool used in software development for checking if JavaScript source code complies with coding rules;  Provided primarily as an online tool, but there are also command- line adaptations;
  • 18. Solution structure  Large scale JavaScript development involves different source types and formats;  Presentation code;  Proxy code;  Third party libs;  Solution structure is tightly coupled with the solution architecture approach;  Physical structure should match the solution architecture abstraction;
  • 19. Solution structure  /scripts  /scripts  /utils  Development helpers  /controllers  Proxy classes to the server methods  /models  Models used for the client and server side  /modules  Modules per functionality  /bootstrappers  Application/module/plugin initializers  /libs  /libs  /components  Custom developed components  /external  External libraries  /content  /content  /images  /images  /css  /css  /media  /media
  • 20. Solution architecture  Plan before execute;  Questions to be answered before the design:  What will be reused?  How many modules depend on other modules?  Are your module sandboxed?
  • 21. Solution architecture  Break your application into small single-purpose parts - modules;  Module pattern gives you implementation privacy, state and code organization;  Provide a way to handle private and public methods and variables;  Protects the code to leak into the global namespace;
  • 22. Solution architecture namespace.modulename = function(module) { var privateVar = some data; module.init = function(){ }; module.doSomething = function(){ internalDoSomething(); }; function internalDoSomething(){ }; return module; }(namespace.modulename || {});
  • 23. Solution architecture  In some point there will be a need to establish module communication;  In order to avoid tight coupling we can utilize the mediator pattern;  The mediator pattern encapsulates how a set of modules interact;
  • 24. Solution architecture
  • 25. Solution architecture  Utilized via Pub/Sub;  Modules communicates via message publishing; ;(function ($) { $.subscribe(namespace/action, var o = $({}); function (data) { $.subscribe = function () { alert(data); o.on.apply(o, arguments); }); }; $.unsubscribe = function () { $.publish(namespace/action, o.off.apply(o, arguments); data) }; $.publish = function () { o.trigger.apply(o, arguments); }; } (jQuery));
  • 26. Solution architecture  Wrapping it all together;  The modules publish events which inform the application that something is happening;  The modules in the system are subscribed to certain events;  The mediator enables the modules to communicate via the PubSub mechanism;
  • 27. Solution architecture
  • 28. Product modules  Utilizing the module pattern;  JavaScript coding pattern;  Module pattern implementation with anonymous closures;  Should be considered:  Every module should be part of a namespace;  Every module can contains sub modules;  What will be the global import of the module;  What will the module export;
  • 29. Product modulesvar namespace.module = (function (import) { var me = {}; // private property var somePrivateVar = Test data; // public property me.publicProperty = Public data; // private method function privateMethod() { somePrivateVar = executed pvt method; } // publicmethod me.publicMethod = function () { return me.publicProperty; }; // the module export return me;}(GLOBAL_IMPORT));
  • 30. Product modules  Module inheritance can be done with module import; namespace.module = (function (baseModule) { var me = {}; // inherit the methods and properties for (key in baseModule) { if (baseModule.hasOwnProperty(key)) { me[key] = baseModule[key]; } } var base_publicMethod = baseModule.publicMethod; // public method override me.publicMethod = function () { return base_publicMethod(); }; // the module export return me; }(module));
  • 31. Dependency management  Which scripts should be loaded before initializing the modules;  Dependency management can be solved by using script loaders:  RequireJS;  LABjs;  Yepnope;  General idea is that your module will not be loaded/executed until the required dependencies are not loaded;
  • 32. Dependency management$LAB yepnope({ .script("framework.js").wait() test : IsAdminUser, .script("plugin.framework.js") yep : normal.js, .script("myplugin.framework.js") nope : [polyfill.js, wrapper.js] .wait(function(){ }); myplugin.init(); framework.init(); framework.doSomething(); }); define(["require", "./relative/name"], function(require) { var mod = require("./relative/name"); });
  • 33. UI Components  Build your UI components in jQuery plugin fashion;  jQuery plugin pattern is well known and understood by most of the UI developers;  Offers simple implementation syntax and offers extensibility;
  • 34. UI Components$.fn.pluginName = function(options){ // Create some defaults, extending them with any options that were provided var settings = $.extend( { location : top, background-color : blue }, options); // return the object back to the chained call flow return this.each(function() // This is the main processor // function that executes on // each selected element // (e.g: jQuery("div")) { var $this = $(this); // usage alert($this); $(document).ready(function() { }); // create a new instance of the plugin}; $(‘selector’).pluginName(options);})(jQuery); });
  • 35. Event Driven Messaging  Allow communication between modules via event publishing managed by pub/sub component;  Each module can publish events, subscribe and unsubscribe to events;
  • 36. Event Driven Messagingapp.usermodule = (function () { app.streammodule = (function () { var me = {}; var me = {}; me.onNewFriendNotificaion = me.post = function(){function(notification){ // do some client logic and alert(notification.from); notify the other modules }; $.publish(on-new-friend- notificaion, { from:user }); me.init = function(){ }; $.subscribe(on-new-friend-notificaion, me.onNewFriendNotificaion); return me; }; }()); me.destroy = function(){ $.unsubscribe(on-new-friend-notificaion, me.onNewFriendNotificaion); }; return me;}());
  • 37. Application routing  Managing navigation between application parts and pages;  Useful for:  Centralizing navigation;  Uri history;  Navigation logging;
  • 38. Application routing<div id="container"> ;(function ($) { <div id="main"></div> var app = $.sammy(#main, function () { <ul id="link"> this.debug = true; <li> <a href="#/form">Form!</a> this.get(#/, function () { </li> this.app.swap(Click form!); <li> }); <a href="#/redirect">Redirect!</a> this.get(#/redirect, function () { </li> this.redirect(#/); <li> }); <a href="#/">Back</a> this.get(#/form, function () { </li> this.partial(files/form.html); </ul> });</div> }); $(function () { app.run(#/); }); })(jQuery);
  • 39. Localization  String localization;  Dates, times, numbers, and currencies;  Use jQuery Globalize plugin for Dates, times, numbers, and currencies;
  • 40. Localization  Store string resources in JSON format so they would be native to client;  Server string resources per culture;  Build language manager for the string resources;  Load the JSON resources into the language manager;  User the language manager to translate plugins, DOM elements and strings;
  • 41. Logging  Useful for tracking modules state, variables and processes while in development;  Natively supported in all of the new modern browsers;  Use an existing logging framework or wrap your logger around the existing browsers logger;
  • 42. Logging var logger = function(){ var logger = {}; window.onerror = function(message, file, line) { logError(file + : + line + nn + message); }; logger.log = function(message){ logError(message); }; function logError(message){ if(console && console.log){ console.log(message); } }; return logger; }();

×