Discover millions of ebooks, audiobooks, and so much more with a free trial

From $11.99/month after trial. Cancel anytime.

Modular Programming with JavaScript
Modular Programming with JavaScript
Modular Programming with JavaScript
Ebook592 pages3 hours

Modular Programming with JavaScript

Rating: 0 out of 5 stars

()

Read preview

About this ebook

Modularize your JavaScript code for better readability, greater maintainability, and enhanced testability

About This Book
  • Design and build fully modular, modern JavaScript applications using modular design concepts
  • Improve code portability, maintainability, and integrity while creating highly scalable and responsive web applications
  • Implement your own loosely coupled code blocks that can power highly maintainable and powerful applications in a flexible and highly responsive modular architecture
Who This Book Is For

If you are an intermediate to advanced JavaScript developer who has experience of writing JavaScript code but probably not in a modular, portable manner, or you are looking to develop enterprise level JavaScript applications, then this book is for you.

A basic understanding of JavaScript concepts such as OOP, prototypal inheritance, and closures is expected.

What You Will Learn
  • Understand the important concepts of OOP in JavaScript, such as scope, objects, inheritance, event delegation, and more
  • Find out how the module design pattern is used in OOP in JavaScript
  • Design and augment modules using both tight augmentation and loose augmentation
  • Extend the capabilities of modules by creating sub-modules using techniques such as cloning and inheritance
  • Move from isolated module pieces to a cohesive, well integrated application modules that can interact and work together without being tightly coupled
  • See how SandBoxing is used to create a medium for all the modules to talk to each other as well as to the core
  • Use the concepts of modular application design to handle dependencies and load modules asynchronously
  • Become familiar with AMD and CommonJS utilities and discover what the future of JavaScript holds for modular programming and architecture
In Detail

Programming in the modular manner is always encouraged for bigger systems—it is easier to achieve scalability with modular programming. Even JavaScript developers are now interested in building programs in a modular pattern. Modules help people who aren't yet familiar with code to find what they are looking for and also makes it easier for programmers to keep things that are related close together.

Designing and implementing applications in a modular manner is highly encouraged and desirable in both simple and enterprise level applications.

This book covers some real-life examples of modules and how we can translate that into our world of programming and application design. After getting an overview of JavaScript object-oriented programming (OOP) concepts and their practical usage, you should be able to write your own object definitions using the module pattern. You will then learn to design and augment modules and will explore the concepts of cloning, inheritance, sub-modules, and code extensibility. You will also learn about SandBoxing, application design, and architecture based on modular design concepts. Become familiar with AMD and CommonJS utilities.

By the end of the book, you will be able to build spectacular modular applications in JavaScript.

Style and approach

This in-depth step-by-step guide will teach you modular programming with JavaScript. Starting from the basics, it will cover advanced modular patterns that can be used in sophisticated JavaScript applications.

LanguageEnglish
Release dateJul 28, 2016
ISBN9781785883996
Modular Programming with JavaScript

Related to Modular Programming with JavaScript

Related ebooks

Programming For You

View More

Reviews for Modular Programming with JavaScript

Rating: 0 out of 5 stars
0 ratings

0 ratings0 reviews

What did you think?

Tap to rate

Review must be at least 10 words

    Book preview

    Modular Programming with JavaScript - Sasan Seydnejad

    (missing alt)

    Table of Contents

    Modular Programming with JavaScript

    Credits

    About the Author

    About the Reviewers

    www.PacktPub.com

    eBooks, discount offers, and more

    Why subscribe?

    Preface

    What this book covers

    What you need for this book

    Who this book is for

    Conventions

    Reader feedback

    Customer support

    Downloading the example code

    Errata

    Piracy

    Questions

    1. What Are Modules and Their Advantages?

    Prelude to modular programming

    The simple rule for creating modules

    A real-life example of modules

    A look at a non-modular example

    Re-factoring to a more modularized approach

    Designing in a modular way

    Summary

    2. Review of Important JavaScript OOP Concepts

    JavaScript objects

    Object type constructors

    Object literal notation

    Function objects

    Functions as object constructors (classes)

    Functions as static objects

    Object literal notation versus function objects

    The this keyword

    Closures

    Encapsulation and scoping

    Inheritance

    Prototype chaining

    Property look up in prototype chaining

    Resetting the constructor property

    Constructor stealing

    Parasitic combination inheritance

    Constructor property

    Native support for inheritance

    Summary

    3. Module Design Pattern

    Module pattern

    Internal private scope in module pattern

    Adding properties to an interface in module pattern

    Object factory module

    Creating loose coupling among modules

    Application core module

    Application Mediator module

    Application non-core modules

    testModule1 implementation

    testModule2 implementation

    Auto-initialization of application modules

    Module initialization and design considerations

    Summary

    4. Designing Simple Modules

    The big picture

    Our application requirements

    Dynamic views

    Designing our SPA main pieces

    Application controller

    Application controller modules

    Page updater module

    Storage handler module

    Communication handler module

    Utilities module

    Message handler module

    Logging handler module

    Creating our first core module

    Structure of our first module

    Using our first module's functionality

    Mapping our module's methods to its interface

    Application view

    Creating the index.html page skeleton

    Creating an object definition for the header

    Generating the Header fragment dynamically

    Generating client application's view dynamically

    Application model

    Creating a module for our application's model

    Creating a logging module

    Summary

    5. Module Augmentation

    Principles of module augmentation

    Implementing module augmentation

    Simple augmentation of ImagesInc_GlobalData

    The order of things in module augmentation

    Loose augmentation of modules

    Loose augmentation of ImagesInc_GlobalData

    Testing ImagesInc_GlobalData data encapsulation

    Tight augmentation of modules

    Tight augmentation of ImagesInc_GlobalData

    Loading ImagesInc_GlobalData augmenting code

    Considerations in tight augmentation

    Generating our application's content area

    Summary

    6. Cloning, Inheritance, and Submodules

    Cloning modules

    Creating instances of a constructor function

    Using the assignment operator for copying objects

    Creating a clone of an object

    Shallow cloning and deep cloning

    Using external libraries for cloning

    Using JSON exploit for cloning

    Creating a custom clone method

    Creating ImagesInc_Utilites module

    Testing our custom cloning method in ImagesInc_Utilites module

    An important aspect of our cloning method

    Inheritance in modules

    Module inheritance using __proto__ object

    Module inheritance using parasitic combination

    Deciding on the module inheritance approach

    Submodules

    Adding submodules using dynamic properties

    Adding submodules using asynchronous properties

    Summary

    7. Base, Sandbox, and Core Modules

    Application architecture overview

    Base module

    Adding general-purpose libraries to the base module

    Sandbox module

    Sandbox module functionality

    Sandbox as a consistent interface

    Sandbox as a security layer

    Sandbox as a communication layer

    Sandbox as a filter

    Implementing multiple instances of the sandbox module

    Advantages of multiple instances of the sandbox

    Isolating the sandbox instances from each other

    Creating a code execution context

    Performance improvements

    Core module

    Core module construction approach

    Core module functionality

    Acting as the controller

    Providing communication bridges

    Initializing and destroying components

    Providing plug-and-play capability

    Providing a centralized approach to handling errors

    Providing application-level extensibility

    Leveraging third party libraries

    Components

    Components required methods

    Binding events to the components elements

    Component design considerations

    Application architectural considerations

    Summary

    8. Application Implementation – Putting It All Together

    The user's view of our application

    Application functionality

    Index page

    Image page

    Favorites page

    Support widget

    Application implementation

    Loading our module files in index.html

    Base module implementation

    Core module implementation

    MainCore module implementation

    Augmenting MainCore module

    Augmenting MainCore using tight augmentation

    Augmenting MainCore using sub-modules

    Component registration with MainCore

    Dynamic loading of components by MainCore

    Storing object definitions in local storage

    Getting a component's object definition from local storage

    Dynamically loading component's resources from the server

    Routing functionality in MainCore module

    Adding a URL to the history object of the browser

    Getting a URL from the history object of the browser

    Publish-subscribe implementation in MainCore

    Registering components for custom events

    Broadcasting custom events by components

    SandBox module implementation

    SandBox module's constructor

    Setting a component's container context in the SandBox instance

    Identifying the SandBox module's instance

    SandBox module considerations

    Application components

    Registering components with MainCore module

    Header component

    Footer component

    Content component

    Handling content area click events

    Handling the Add To Favorite link click event

    Handling an image click event

    Content area generator methods

    NotificationWidget component

    NotificationWidget's model

    Required methods of the notificationWidget component

    Rendering notificationWidget

    GlobalData module

    Summary

    9. Modular Application Design and Testing

    Advantages of writing automated tests

    Different types of automated tests

    Unit testing

    TDD unit tests

    BDD unit tests

    TDD versus BDD

    Test coverage

    Integration testing

    End to end testing

    A simple start to writing our unit tests

    Writing unit tests without any unit testing frameworks

    Adding an AppTester module to our application

    Adding unit test suites to our test-runner

    CookieHandler module unit tests

    Running CookieHandler unit tests

    Cleaning up after running our unit tests

    Writing unit tests using third party frameworks

    Introduction to Jasmine

    Setting up Jasmine

    Creating our Jasmine spec file

    Running our Jasmine unit tests

    Exploring Jasmine further

    Introduction to Mocha

    Setting up Mocha

    Chai

    Creating our Mocha spec file

    Running our Mocha-Chai unit tests

    Exploring Mocha further

    Summary

    10. Enterprise Grade Modular Design, AMD, CommonJS, and ES6 Modules

    Revisiting index.html file

    Introducing Asynchronous Module Definition

    Defining modules using AMD format

    Importing AMD modules

    Introducing RequireJS

    Downloading RequireJS

    A test project for creating and loading AMD modules

    Creating a simple AMD module

    Consuming our person AMD module

    Loading dependencies of dependencies

    Loading and consuming non-AMD modules

    Setting paths in the config object

    Creating shims for non-AMD modules

    Refactoring Images Inc. application to use AMD format

    Modifying Core submodules into AMD modules

    Loading our non-AMD modules using RequireJS

    Setting up our application's config.js file

    Booting up our application using RequireJS

    CommonJS

    Implementing a CommonJS module

    ECMAScript 6 modules

    Defining an ES6 module

    Consuming an ES6 module

    Module loading sequence in the browsers for ES6 modules

    Summary

    Index

    Modular Programming with JavaScript


    Modular Programming with JavaScript

    Copyright © 2016 Packt Publishing

    All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.

    Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.

    Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.

    First published: July 2016

    Production reference: 1150716

    Published by Packt Publishing Ltd.

    Livery Place

    35 Livery Street

    Birmingham B3 2PB, UK.

    ISBN 978-1-78588-065-0

    www.packtpub.com

    Credits

    Author

    Sasan Seydnejad

    Reviewers

    Joe Dorocak

    Muhammad Piracha

    Commissioning Editor

    Veena Pagare

    Acquisition Editor

    Smeet Thakkar

    Content Development Editor

    Mayur Pawanikar

    Technical Editor

    Anushree Arun Tendulkar

    Copy Editor

    Safis Editing

    Project Coordinator

    Nidhi Joshi

    Proofreader

    Safis Editing

    Indexer

    Mariammal Chettiyar

    Graphics

    Disha Haria

    Production Coordinator

    Nilesh Mohite

    Cover Work

    Nilesh Mohite

    About the Author

    Sasan Seydnejad has more than a decade of experience in web UI and frontend application development using JavaScript, CSS, and HTM in .NET and ASP.NET environments. He specializes in modular SPA design and implementation, responsive mobile-friendly user interfaces, AJAX, client architecture, and UX design, using HTML5, CSS3, and their related technologies. He implements framework-less and framework-based applications using Node.js, MongoDB, Express.js, and AngularJS. He is the holder of the U.S. patent for a user interface for a multi-dimensional data store—US Patent 6907428.

    Writing this book has been an interesting journey and a lot of work but rewarding at the same time. I would like to thank my family who has always motivated me to learn and progress in my life as well as to help others along the way.

    I would also like to thank my friends, my managers, my colleagues and all the other people who have been a positive influence in my life. You have helped me to grow personally and professionally.

    Special thanks to my friend Taswar Bhatti for encouraging me to write this book and the book's Content Development Editor, Mayur Pawanikar for keeping me focused on the goal. Also, my book reviewers and all the people in PACKT publishing who made this book possible. My gratitude to JavaScript and open source community as a whole, thank you for your support through out the years.

    About the Reviewers

    Joe Dorocak, whose Internet moniker is Joe Codeswell, is a very experienced programmer. He enjoys creating readable code that implements the project requirements efficiently and understandably. He considers writing code akin to writing poetry.

    Joe prides himself on the ability to communicate clearly and professionally. He considers his code to be a form of communication, not only with the machine platforms upon which it will run, but also with all the human programmers who will read it in the future.

    Joe has been employed as a direct employee or a contractor by IBM, HP, GTE/Sprint, and other top-shelf companies. He is presently concentrating on the web app and web project consulting, coding primarily, but not exclusively, in Python and JavaScript. For more details, visit https://www.linkedin.com/in/joedorocak.

    Muhammad Piracha is director of engineering at Bamboo Solutions Corporation, based in Reston, Virginia. Bamboo Solutions is a leading provider of software solutions for the Microsoft® SharePoint® platform. Muhammad has over 18 years experience building document management software applications using various Microsoft products.

    Currently he oversees several teams across engineering, research and quality assurance to constantly improve the existing portfolio of over 50 products. He is a major driving force in helping the company to develop strategy, architecture, and direction for new initiatives in the SharePoint Online and Office 365™ space.

    www.PacktPub.com

    eBooks, discount offers, and more

    Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at for more details.

    At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.

    eBooks, discount offers, and more

    https://www2.packtpub.com/books/subscription/packtlib

    Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.

    Why subscribe?

    Fully searchable across every book published by Packt

    Copy and paste, print, and bookmark content

    On demand and accessible via a web browser

    Preface

    There are many JavaScript books on the market these days, and some of them are very good. However, most of them focus on various aspects of the language itself or using certain frameworks to build JavaScript applications. In this book, we are going to take a different approach and look at the architectural design of creating JavaScript applications based on modules, without the need for third-party frameworks.

    Creating a good application is more than just writing good code, it is also about how different pieces of the application work and interact with each other. Another characteristic of a good application is its ability to be easily maintained, scaled and extended as needed. A proper modular design enables us to achieve all such goals in our application seamlessly.

    In the beginning of this book, I'll be introducing you to the fundamentals of JavaScript modules and the concepts behind a good modular design. Leveraging these concepts, we'll be building an application together, step-by-step, so we can apply what we learn in practice. I recommend reading the chapters in the sequence that they are presented so you can follow along with ease and observe how our design evolves over time.

    I would very much encourage you to develop the application pieces with me, as the intent of this book is to be very hands-on, and I would like you to feel as a member of the development team for this application.

    As in the real world, we will be re-factoring our code-base a few times during the development phase, in order to implement the new concepts as they are introduced and improve the quality of our application.

    Keep in mind that we will be creating a client-side application, and as such, there is no server-side code involved. Nonetheless, many concepts that we will be covering regarding modules and modular architecture can be applied to server-side applications too.

    Also, as this book is an introduction to modular JavaScript application design, we will develop a Proof of concept (POC)-grade application together which can provide a good starting point for your own projects.

    I have taken a minimalist approach in the implementation, and as a result, we will be using very few third-party libraries in our development process. Therefore, instead of focusing on studying new libraries and how to work with them, you can focus on the application's architecture instead. Once we create a solid foundation, we can incorporate other libraries into our design as required.

    For the purposes of clarity, I have shied away from writing fancy code, so you don't have to spend much time trying to understand the intricacies of the code, as opposed to the big picture and how the pieces fit and work together.

    Note that this book is meant for people who have a good understanding of JavaScript language, but would like to learn more about JavaScript client-side application design. If you find yourself having trouble with the language itself, you can always refer to online resources and the JavaScript community. This community consists of many smart and helpful people who can, and will be willing to answer your questions. I, for one, am very grateful to the community for its help in my professional growth over the years.

    I hope you'll find the book informative and by seeing the benefits of a modular architecture, will use the concepts presented in this book in your own future projects.

    What this book covers

    Chapter 1, What Are Modules and Their Advantages?, introduces you to the concept of modules and how they can help us design a robust and scalable application.

    Chapter 2, Review of Important JavaScript OOP Concepts, covers an overview of some of the important OOP concepts in JavaScript which are necessary for the design and implementation of the modules in our application.

    Chapter 3, Module Design Pattern, introduces a very common pattern in creating modules in JavaScript and shows how this pattern can be implemented.

    Chapter 4, Designing Simple Modules, uses the module pattern to create simple modules which work together to form the building blocks of our application.

    Chapter 5, Module Augmentation, shows the use of various techniques to add more functionality to our modules so that we can extend their capabilities further.

    Chapter 6, Cloning, Inheritance, and Submodules, covers how to create modules based on other modules in our application, as well as some more techniques to enhance our modules.

    Chapter 7, Base, Sandbox, and Core Modules, introduces some of the main pieces of our application and demonstrates how to create loose coupling among our application modules.

    Chapter 8, Application Implementation – Putting It All Together, shows us how to apply all the concepts that we have learned regarding modular architectural design, in order to implement all the pieces of our application.

    Chapter 9, Modular Application Design and Testing, covers how to test our application modules using either plain JavaScript or third-party frameworks.

    Chapter 10, Enterprise Grade Modular Design, AMD, CommonJS, and ES6 Modules, introduces different modular formats in JavaScript which can be used to design modules, as well as how modules can be imported and exported in our application using these formats.

    What you need for this book

    You will require any modern browser (IE 9+, Chrome, Safari, Firefox) and any OS that can run a modern browser from the preceding list.

    The third-party library required would be jQuery 1.8+.

    For the later chapters, the following are the third-party libraries:

    Jasmin 2+

    Mocha (latest version)

    Chai (latest version)

    RequireJS (latest version)

    Who this book is for

    If you are an intermediate to advanced JavaScript developer who has an experience of writing JavaScript code, but probably not in a modular portable manner, or you are looking to develop enterprise-level JavaScript applications, then this book is for you.

    A basic understanding of JavaScript concepts such as OOP, prototypal inheritance, and closures is expected.

    Conventions

    In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.

    Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: Notice that I have created a function and called it MyObjDefinition.

    A block of code is set as follows:

    function doAddition(num1, num2){

      return num1 + num2;

    }

    Note

    Warnings or important notes appear in a box like this.

    Tip

    Tips and tricks appear like this.

    Reader feedback

    Feedback from our readers is always welcome. Let us know what you think about this book—what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of.

    To send us general feedback, simply e-mail <[email protected]>, and mention the book's title in the subject of your message.

    If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.

    Customer support

    Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.

    Downloading the example code

    You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

    You can download the code files by following these steps:

    Log in or register to our website using your e-mail address and password.

    Hover the mouse pointer on the SUPPORT tab at the top.

    Click on Code Downloads & Errata.

    Enter the name of the book in the Search box.

    Select the book for which you're looking to download the code files.

    Choose from the drop-down menu where you purchased this book from.

    Click on Code Download.

    You can also download the code files by clicking on the Code Files button on the book's webpage at the Packt Publishing website. This page can be accessed by entering the book's name in the Search box. Please note that you need to be logged in to your Packt account.

    Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:

    WinRAR / 7-Zip for Windows

    Zipeg / iZip / UnRarX for Mac

    7-Zip / PeaZip for Linux

    The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/ModularProgrammingwithJavaScript. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!

    Errata

    Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books—maybe a mistake in the text or the code—we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.

    To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.

    Piracy

    Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.

    Please contact us at <[email protected]> with a link to the suspected pirated material.

    We appreciate your help in protecting our authors and our ability to bring you valuable content.

    Questions

    If you have a problem with any aspect of this book, you can contact us at <[email protected]>, and we will do our best to address the problem.

    Chapter 1. What Are Modules and Their Advantages?

    In this very first chapter, I will provide you with an overview of the modular design approach in application development as it relates to JavaScript applications.

    I will also mention parallels between the modular style of application architecture and the real-life examples of this conceptual design.

    Hopefully, as you read along, you'll be able to relate to

    Enjoying the preview?
    Page 1 of 1