Presentation is loading. Please wait.

Presentation is loading. Please wait.

Web Applications Client Side Development

Similar presentations


Presentation on theme: "Web Applications Client Side Development"— Presentation transcript:

1 Web Applications Client Side Development
Martin Kruliš by Martin Kruliš (v1.0)

2 JavaScript in Browser (Revision)
Web Page Context All scripts are executed only once (when loaded) Other code must be in event handlers Application state (memory) is lost on page refresh Current browsers allow opening multiple windows or tabs (i.e., display multiple pages) Each page must have its own isolated context Context is represented by an object for global variables (window) Also holds all browser interfaces, most importantly document, which provides access to DOM HTML document and CSS styles currently being rendered Remember that the page is also refreshed when browsing (or using back/forward buttons for history navigation). by Martin Kruliš (v1.0)

3 Document Object Model …
DOM (Revision) body h1 p img Document src DOM Example Document Object Model … alt html Document Object Model <html> <body> <h1>DOM Example</h1> <p> Document Object Model is an API … </p> <img src="url" alt="text"> ... </body> </html> by Martin Kruliš (v1.0)

4 DOM (Revision) DOM Node Traversing Node.firstChild, Node.lastChild
Node.childNodes Node.nextSibling, Node.previousSibling Node.parentNode, Node.parentElement Node.nodeName, Node.nodeValue Node.attributes – relevant for elements only Document.documentElement – root element Document.getElementsByTagName(tagName) Document.getElementById(id) by Martin Kruliš (v1.0)

5 DOM (Revision) DOM Content Manipulation Extra Features
Document.createElement(), … Node.appendChild(), Node.insertBefore() Node.replaceChild(), Node.removeChild() Element.getAttribute(), Element.setAttribute() Element.removeAttribute() Node.cloneNode(deep) Extra Features Node.innerHTML, Node.outerHTML Document.evaluate(xpath) by Martin Kruliš (v1.0)

6 Events (Revision) Event Model
Top-level scripts are executed immediately Other code can be attached to various events One event loop processed in single thread If the event is not processed, it bubbles up DOM Tree Processes one event at a time Mouse Moved User Clicked Event Queue Dispatcher Loading Finished Target Window Resized Target element is found … by Martin Kruliš (v1.0)

7 Events (Revision) Event Handling
Events may be handled by callback functions Attached directly in HTML <button onclick="js code handling the event"> Or by Javascript code myButton.onclick = function(event) { ... } or myButton.addEventListener('click', fnc, capture); Todays choice – addEventListener() Allows multiple handlers on one event Works on any DOM element (not just HTML) Allows early event capturing by Martin Kruliš (v1.0)

8 DOM DOM Issues DOM is generic API Writing DOM code is rather tedious
It aims to cover functionality, not to streamline code It is also being steered by other languages (e.g. XML) Writing DOM code is rather tedious Considering most task have repetitive pattern (e.g., binding event handlers) Compatibility issues in mainstream browsers DOM1 is supported, DOM2 mostly, and DOM3 partially by Martin Kruliš (v1.0)

9 jQuery jQuery Library Modern JavaScript library for basic operations
Easy to learn and use Lightweight footprint Supports almost all currently used browsers Key features Simplified DOM traversal and manipulation Event handling CSS based animations and effects Unified AJAX API with support for data (de)serialization Extendable with plugins and UI libraries by Martin Kruliš (v1.0)

10 jQuery Object jQuery Object “Select and Do” Philosophy
Function object in global name jQuery and $ Acts as a function that returns set of nodes and as a container object for library functions “Select and Do” Philosophy Select a set of DOM nodes Apply (a sequence of) operation(s) on the whole set of selected nodes Most methods support invocation chaining $(selector).doIt().doAnother().doSometingElse(); by Martin Kruliš (v1.0)

11 jQuery Selectors Selector Selects set of DOM nodes for further usage
$("selector") or $(DOMnode) or $("HTMLfragment") jQuery Selectors are inspired by CSS3 selectors "div" – select elements of given name "#id" – select element by its ID ".class" – select elements with specific CSS class "ancestor descendant" – express DOM relations :disabled, :visible, :checked, … Subsequent operations work on the whole set $(".secret").hide(); by Martin Kruliš (v1.0)

12 jQuery DOM Manipulation
Manipulating HTML Structure Wrappers for DOM manipulation functions prepend(), append(), before(), after() – insert content before/after inside/outside selected elements remove(), empty(), detach() – remove (child) nodes replaceAll(), replaceWith() html(), text() – manipulate with content clone() – create a deep copy of the element attr(), prop(), removeAttr(), removeProp() Attr ~ HTML attributes, prop ~ properties (checked, …) Reading methods take only the first element in set by Martin Kruliš (v1.0)

13 jQuery DOM Traversal Traversing DOM Tree Similar to XPath processing
Using set of nodes as starting point add() – unite one set with another children() – get children of all nodes next() – get next sibling for each node parents() – get all node ancestors Node set filtering filter() – filter by functor or selector not() – remove given nodes (or by selector) slice() – get a subrange (by indices) The selected functions are only illustrative. There are many more of them. by Martin Kruliš (v1.0)

14 jQuery Events Event Handlers Binding Bind handlers by event name
on(), off(), one() jQuery.proxy() – binds functor within a context Triggering events - trigger(), triggerHandler() Document loading events $(document).load(), .unload(), .ready() Specialized event handling/triggering functions click(), mousedown(), hover(), keydown(), … Event object is wrapped in jQuery.Event $(document).ready(handler) is special event that is triggered when all document contents (images, scripts, …) is loaded. It has also two shorthand notations $().ready(handler) and $(handler). by Martin Kruliš (v1.0)

15 jQuery CSS Handling Cascading Style Sheets Manipulation
Reading writing all properties css(property [, value]) Manipulation with CSS classes addClass(), removeClass(), hasClass(), toggleClass() Element position position(), offset() Element size height(), width(), innerHeight(), outerWidth() The CSS management mechanism can be overridden for specific properties by jQuery.cssHooks() by Martin Kruliš (v1.0)

16 jQuery Other Features Animations (Effects)
Achieved using CSS properties and timers Designed before CSS3 AJAX Wrapper, Deferred objects Now we have ES6 promises and fetch API jQuery UI Library of useful UI components by Martin Kruliš (v1.0)

17 Application State Management
Client Application Model Event-driven (similar to other UI frameworks) State is kept in memory (JavaScript variables) HTML + CSS is used for UI presentation Application State State is lost when the page is refreshed On browsing, submitting forms, history navigation, … Can be persisted At server side, cookies, local storage, URL Some refreshes may be avoided Manual handling of browsing, submitting forms by AJAX by Martin Kruliš (v1.0)

18 Embedding State into DOM
Using DOM as Data Storage Some DOM data are used not only for visualization, but they also represent the state Advantages Initial state may be encoded directly to HTML HTML and state are always in sync Trivial to implement Disadvantages Leads to complex (spaghetti) code in more complex situations May prevent code decomposition and reuse State must be modified (twisted) to match visualization Therefore, embedding state in DOM may be used only in simple-enough scenarios. E.g., when the application uses traditional approach (HTML is rendered at server side) and only few small features need to be handled at client side. by Martin Kruliš (v1.0)

19 Embedding State into DOM
Example: CSS Classes as Flags CSS class assigned to an element is typically used to alter appearance It may also be used as a state indicator $(".selectable").click(e => { $(e.currentTarget).toggleClass("selected"); }); $("#saveBtn").click(e => { const items = []; $(".selected").each((idx, elem) => { items.push($(elem).attr("id")); ...}); by Martin Kruliš (v1.0)

20 Identifier is auto-converted to camelCase
Data Attributes Data in DOM Special data attributes data-* <a href="…" data-confirm-msg="Really go to…?"> Easily accessible by Javascript Using regular HTML5 API confirm(mylink.dataset.confirmMsg); mylink.dataset.clicked = true; Using jQuery wrapper $("a[data-confirm-msg]").click(e => { if (!confirm($(e.currentTarget) data("confirmMsg")) e.preventDefault(); }); Identifier is auto-converted to camelCase by Martin Kruliš (v1.0)

21 Callback gets a list of changes after they are completed
Mutation Observer Mutation Observer Designed to replace DOM mutation events Observes selected DOM nodes for changes and triggers a callback every time a change occurs var observer = new MutationObserver(mutations => { mutations.forEach(mutation => { // handle the mutation }); observer.observe(targetNode, { attributes: true, childList: true, subtree: true, Callback gets a list of changes after they are completed The DOM mutation events were deprecated due to their performance issues. The MutationObserver is designed to provide similar functionality in a more efficient way. All the DOM modifications are performed first and then the observer’s callback is invoked with a list of changes. Monitor attribute changes, child node add/remove and do it recursively on the subtree by Martin Kruliš (v1.0)

22 Editable Content Editable Content
A way how to turn browser into WYSIWYG editor Selected element or the whole document becomes interactive and the user may change the contents For selected elements element.contentEditable (true, false, inherit) element.isContentEditable For the whole document document.designMode (on, off) Particularly useful for a page inside <iframe> by Martin Kruliš (v1.0)

23 Editable Content Using Commands when Editing Content
Commands modify the text selection, insert new contents, or change editing parameters document.execCommand(cmd, defautUI, value) Affects currently active (focused) editable element Additional support methods queryCommandSupported() queryCommandEnabled() queryCommandValue() queryCommandState() queryCommandIndeterm() execCommand() arguments command – name of te command as string defaultUI – whether to show default UI controls (currently not supported in Mozilla) valueArg – argument of the command (depends on the command type) QueryCommand… Value – returns value on current selection State – whether the command has been invoked on current selection Indeterm – whether a formatting command is in a indeterminate state on current selection by Martin Kruliš (v1.0)

24 Editable Content Editing Commands copy, cut, paste
delete, forwardDelete undo, redo insertText, insertParagraph, insertImage createLink bold, italic foreColor, backColor enableObjectResizing styleWithCSS by Martin Kruliš (v1.0)

25 Some Useful Techniques
Content Hiding The entire content of the web (page) is loaded Currently irrelevant parts are hidden by a script Used in various UI patterns Page tabs, Accordion, Expanding tree, Form wizard, … Content Replication Repetitive parts of HTML structure Data table rows, multi-input forms, … Hidden HTML fragment (template) The template is cloned, inserted at a proper place, and shown by Martin Kruliš (v1.0)

26 Some Useful Techniques
Content Hiding Example .hidden { display: none; } <section id="tab1" class="tab"> ... </section> <section id="tab2" class="tab hidden"> function showTab(id) { $(".tab").addClass("hidden"); $(`#${id}`).removeClass("hidden"); } by Martin Kruliš (v1.0)

27 Some Useful Techniques
AJAX Overrides Action Buttons Simple operations that does not require input Switch state, delete, generate password, start service, … Designed as a hyperlink, but handled by JavaScript Click event initiates AJAX POST request instead AJAX Forms Submit event is overridden, form contents is assembled into POST request and sent by AJAX request Much simpler handling of user errors (invalid fields) Does not require session storage like sticky forms by Martin Kruliš (v1.0)

28 MVC Pattern Model-View-Controller at Client Side Controller View Model
Process user actions and handles business logic Controller Keeps client-side data and manages their sync. with server side (if necessary) Event callbacks View Model Renders data (Javascript structures, JSON, XML, …) into HTML fragments by Martin Kruliš (v1.0)

29 MVVM Pattern Model-View-Viewmodel
Simplifies data presentation especially in SPA View Model Bidirectional data bindings The ViewModel is sometimes called Binder. Furthermore, the data bindings are typically handled by declarative programming rather than imperative. View Model ViewModel Presentation logic (DOM, event handling) Data for presentation (JS structures, model projection) Data for business logic (using server API representation) by Martin Kruliš (v1.0)

30 Angular Angular (2+) Library
Open source SPA framework, propelled by Google Adopts MVC and MVVM patterns Data bindings are declarative (embedded in HTML) Microsoft TypeScript Typed version of JavaScript ES6 + Types + Annotations Components Component class holds the data Template holds augmented HTML With possible bindings to component data by Martin Kruliš (v1.0)

31 Bidirectional data binding
Angular Example @Component({ selector: 'my-app', templateUrl: './user.component.html', styleUrls: ['./user.component.css'] }) export class UserComponent implements OnInit { user: User = { id: 1, name: 'Martin', surname: 'Krulis', }; constructor() { ... } ngOnInit() { ... } ... } <h1>{{ user.name | uppercase }}</h1> <div> <label>name: <input [(ngModel)]="user.name" placeholder="name"> </label> <label>surname: <input [(ngModel)]="user.surname" </div> Bidirectional data binding by Martin Kruliš (v1.0)

32 One-way Rendering Only state => html rendering function is necessary (no bindings) Update is typically triggered after UI action Controller Event callback (user action) Update Perhaps the greatest problem of this approach is that the re-rendering may be computationally demanding. Therefore, many techniques like caching, virtual DOM, and component decomposition are required to achieve adequate performance. DOM State Rendering function(s) by Martin Kruliš (v1.0)

33 React React.js UI Library
Open source, propelled by Facebook and Instagram Key features Separation of concepts (individual UI components) One-way data flow Child component cannot modify its parent Actions are propagated up through callback Virtual DOM Aggregate changes, so fewer modifications to real DOM are required when a component re-renders itself JSX – JavaScript language extension Interleaves JS with pseudo-XHTML by Martin Kruliš (v1.0)

34 Component rendering is hierarchical
React Example class Box extends Component { state = { isOpen: true }; toggleOpen = () => { this.setState({ isOpen: !this.state.isOpen }); } render() { const { items, delete } = this.props; <div onClick={this.toggleOpen}> {this.state.isOpen && <ul> items.map(item => <li> {item} <DeleteIcon onClick={delete(item)} /> </li>); </ul>} </div> Meanwhile, in another component … items = [ … ]; ... const deleteItem = item => () => { this.items = this.items.filter( it !== item ); } render() { <Box items={this.items} delete={this.deleteItem} /> Component rendering is hierarchical Render is called again if component properties (or internal state) is changed by Martin Kruliš (v1.0)

35 React Rendering and Optimizations
Rendering is triggered when a component inputs have changed Component is re-rendered only when its input changes Page Real DOM Component Component One-time update when the whole virtual DOM is updated Virtual DOM by Martin Kruliš (v1.0)

36 Discussion by Martin Kruliš (v1.0)


Download ppt "Web Applications Client Side Development"

Similar presentations


Ads by Google