Browser Routing Design Patterns in JS

Slides:



Advertisements
Similar presentations
AngularJS Routing Routes, Route Parameters, Templates, Location, Navigation SoftUni Team Technical Trainers Software University
Advertisements

AngularJS Services Built-in and Custom Services SoftUni Team Technical Trainers Software University
AngularJS Directives Defining Custom Directives SoftUni Team Technical Trainers Software University
AMD and RequireJS Splitting JavaScript Code into Dependent Modules Software University Technical Trainers SoftUni Team.
Sessions and Cookies State Management, Cookies, Sessions, Hidden Fields SoftUni Team Technical Trainers Software University
Web Storage and Cookies Cookies, Local and Session Storage SoftUni Team Technical Trainers Software University
First Steps in PHP Creating Very Simple PHP Scripts SoftUni Team Technical Trainers Software University
AngularJS Best Practices High Quality SPA Applications SoftUni Team Technical Trainers Software University
Version Control Systems
Magento Basics Getting started developing for Magento
Auto Mapping Objects SoftUni Team Database Applications
C# MVC Frameworks – ASP.NET
ASP.NET Essentials SoftUni Team ASP.NET MVC Introduction
Web API - Introduction AJAX, Spring Data REST SoftUni Team Web API
Introduction to MVC SoftUni Team Introduction to MVC
Deploying Web Application
Thymeleaf and Spring Controllers
WordPress Introduction
Build a WordPress Site A Real Life Example: Create a Fully Functional WP Business Web Site from Scratch Building a WP Site SoftUni Team Technical Trainers.
JavaScript Applications
Introduction to Entity Framework
Source Control Systems
ASP.NET Integration Testing
ASP.NET Unit Testing Unit Testing Web API SoftUni Team ASP.NET
Classes, Properties, Constructors, Objects, Namespaces
Mocking tools for easier unit testing
JavaScript Applications
State Management Cookies, Sessions SoftUni Team State Management
EF Code First (Advanced)
PHP MVC Frameworks MVC Fundamentals SoftUni Team Technical Trainers
Entity Framework: Code First
Unit Testing with Mocha
C#/Java Web Development Basics
MVC Architecture. Routing
Creating React Components with JSX and Babel
Front-End Framework for Responsive Web Sites
Entity Framework: Relations
Caching Data in ASP.NET MVC
Array and List Algorithms
Modules, Babel, RequireJS, Other JavaScript Module Systems
The Right Way Control Flow
ASP.NET Razor Engine SoftUni Team ASP.NET MVC Introduction
MVC Architecture, Symfony Framework for PHP Web Apps
ASP.NET SignalR SoftUni Team C# MVC Frameworks Technical Trainers
AJAX and jQuery AJAX AJAX Concepts, XMLHttpRequest, jQuery AJAX: $.ajax(), $.get(), $.post() jQuery AJAX XMLHttpRequest SoftUni Team Technical Trainers.
ASP.NET MVC Introduction
Databases Advanced Course Introduction SoftUni Team Databases Advanced
Best Practices and Architecture
C# Web Development Basics
Creating UI elements with Handlebars
Best practices and architecture
Design & Module Development
Magento Basics part 2 Modules & Themes Stenik Group Ltd. Magento
WordPress Plugins Popular WP Plugins: Sliders, Forms, Contacts, SEO, Forum, Photo Gallery, e-Commerce WordPress Plugins SoftUni Team Technical Trainers.
Extending functionality using Collections
ASP.NET REST Services SoftUni Team ASP.NET REST Services
ASP.NET Filters SoftUni Team ASP.NET MVC Introduction
Making big SPA applications
Manual Mapping and AutoMapper Library
C# Advanced Course Introduction SoftUni Team C# Technical Trainers
Course Overview, Trainers, Evaluation
Scheduled Tasks and Web Socket
Introduction to TypeScript & Angular
Train the Trainers Course
Software Quality Assurance
Version Control Systems
JavaScript Frameworks & AngularJS
Lean .NET stack for building modern web apps
JavaScript: ExpressJS Overview
Iterators and Generators
Presentation transcript:

Browser Routing Design Patterns in JS Routing and Patterns Browser Routing Design Patterns in JS Routing SoftUni Team Technical Trainers Software University http://softuni.bg

Table of Contents Routing Concepts Basic Router Sammy.js Overview Design Patterns

Have a Question? sli.do #JSAPPS

Navigation for Single Page Apps Routing Concepts Navigation for Single Page Apps

Navigation using Routing What is Routing? Routing allows navigation, without reloading the page It's a pivotal element of writing Single Page Applications Link HTML Router Standard Navigation Navigation using Routing

How Routers Work A Router loads the appropriate content when the location changes E.g. when the user manually enters an address Conversely, a change in content is reflected in the address bar E.g. when the user clicks on a link Benefits: Load all scripts only once Maintain state across multiple pages Browser history can be used Build User Interfaces that react quickly

Writing a Simple Browser Router Live Demo Writing a Simple Browser Router

Routing with Sammy.js Overview and Examples

Sammy.js Overview Sammy is a lightweight routing library Modular design with plugins and adapters Requires with jQuery Many additional features const app = Sammy('#main', function() { this.get('index.html', () => { this.swap('Index'); }) });

npm install --save sammy node_modules/sammy/lib/ Installation Download Sammy using WebStorm's terminal Or download from sammyjs.org Browser builds will be located in: Sammy requires jQuery to work! npm install --save sammy node_modules/sammy/lib/ Note: It's best if your project has a package.json file

Hello Sammy index.html <!DOCTYPE html> <head> <meta charset="UTF-8"> <title>Hello Sammy</title> <!-- Include jQuery and Sammy distributions --> </head> <body> <header> <h1>Hello Sammy</h1> <a href="index.html">Home</a> <a href="about">About</a> <a href="contact">Contact</a> </header> <div id="main"></div> </body> </html> index.html

Hello Sammy (2) app.js const app = Sammy('#main', function () { this.get('index.html', () => { this.swap('<h2>Home Page</h2>'); }); this.get('about', () => { this.swap('<h2>About Page</h2>'); this.get('contact', () => { this.swap('<h2>Contact Page</h2>'); $(() => { app.run();

Application Initialization Create a Sammy instance to initialize your application You may have multiple apps running Each selector can only hold one app If you refer to it again, it extends the functionality Invoke library Element selector const app = Sammy('#main', function () { // Define routes and other logic here }); $(() => app.run()); // Activate

Creating Routes The main building block of Sammy is the route Defined by method and address (URI) Place this block inside a Sammy initializer: A note on using this: it holds a reference to the router object, but may not work correctly in an arrow function Route Method Route address this.route('get', 'about', function() { this.swap('<h2>Contact Page</h2>'); });

Route Aliases Each method has an alias for shorter code this.get('catalog', loadBooks) this.post('login', userLogin) this.put('catalog/:bookId', updateBook) this.del('catalog/:bookId', deleteBook)

URL Parameters Parameters allow for dynamic routes E.g. products in a catalog will load the same page You can get the whole path using this.path Parameter name Receive context this.get('catalog/:productId', (context) => { console.log(context.params.productId); }); Access passed in value

Handling Forms Forms inside the main element are automatically handled Route address Route method <form action="login" method="post"> User: <input name="user" type="text"> Pass: <input name="pass" type="password"> <input type="submit" value="Login"> </form> this.post('login', (context) => { console.log(context.params.user); console.log(context.params.pass); }); Names of inputs

Integrating Handlebars Download and include the Handlebars source in your HTML Include sammy.handlebars.js (found under lib/plugins) Load the plugin inside a Sammy initializer: Create a RenderContext with render, load or partial this.use('Handlebars', 'hbr'); Template file extension

Load and swap in the template Using Handlebars greeting.hbr <h1>{{title}}</h1> <p>Hello, {{name}}!</p> app.js const app = Sammy('#main', function () { this.use('Handlebars', 'hbr'); this.get('#/hello/:name', function() { this.title = 'Hello!' this.name = this.params.name; this.partial('greeting.hbr'); }); $(() => app.run()); Load and swap in the template

Using Handlebars (2) Load a list of partial templates (inside a route definition): The callback will be executed once all partials are loaded Templates are cached – there's no need to manually cache them this.loadPartials({ firstPartial: 'path-to/first.hbr', secondPartial: 'path-to/second.hbr', thirdPartial: 'path-to/third.hbr' }).then(function(context) => { console.log(context.partials); this.partial('pageTemplate.hbr'); });

Additional Features Redirect Custom events Useful plugins (found under lib/plugins): Storage and Session OAuth2 this.redirect('#/other/route'); this.redirect('#', 'other', 'route'); // Register event handler this.bind('event-name', eventHandlerFunction); // Raise event this.trigger('event-name', data);

Programming Patterns Organizing Your Code

What are Design Patterns Design Patterns are general approaches to solving commonly occurring problems They provide: tested, proven programming paradigms guidelines to organizing our code a common vocabulary between developers Using a pattern may increase complexity – misuse often creates more problems than it solves

Splitting Your Code Splitting your code aims to separate concerns (only change the parts that need to be changed) Sample code organization Main script Requester (Remote API) Authenticator Router View Controllers

Live Demo Organizing Code

Live Exercises in Class (Lab) Practice: Routing Live Exercises in Class (Lab)

Summary Browser Routing allows SPAs to use history Sammy.js is a simple routing library Modular code is more maintainable const app = Sammy('#main', function () { this.get('index.html', () => { this.swap('<h1>Index Page</h1>'); }) });

Routing https://softuni.bg/courses/ © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

License This course (slides, examples, demos, videos, homework, etc.) is licensed under the "Creative Commons Attribution- NonCommercial-ShareAlike 4.0 International" license © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.

Free Trainings @ Software University Software University Foundation – softuni.org Software University – High-Quality Education, Profession and Job for Software Developers softuni.bg Software University @ Facebook facebook.com/SoftwareUniversity Software University Forums forum.softuni.bg © Software University Foundation – http://softuni.org This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike license.