This document discusses JavaScript code architecture and module patterns using RequireJS. It begins with an introduction to RequireJS and how it can be used to dynamically load modules and their dependencies. Next, it covers defining modules with and without dependencies, and how to return maker functions from modules to create "classes". The document concludes with notes on best practices for modules and an overview of RequireJS configuration options to integrate third-party libraries.
Backbone.js helps structure you javascript application code in a scalable way.
In this keynote I demonstrate how to use it in a simple walk-through example, and discuss the advantages of using an MVC framework.
This document discusses using jQuery with Drupal. It provides an overview of jQuery and its benefits over JavaScript. It then discusses guidelines for using jQuery in Drupal modules and themes, such as adding JavaScript files with drupal_add_js() and defining behaviors. Examples are given of simple DOM manipulation with JavaScript, jQuery, and best practices for jQuery in Drupal.
jQuery is a JavaScript library which allows you to develop solutions with less code, in less time. You can build interactive prototypes for your prospective clients, or take an existing solution and add new dynamic behaviour with little effort.
We will see how jQuery can be used to quickly and concisely apply JavaScript behaviour to your web app. It will cover selectors, Ajax, DOM manipulation and more. The aim: to produce lean unobtrusive JavaScript with jQuery.
Getting the Most Out of jQuery Widgetsvelveeta_512
The document discusses strategies for building modular widgets in jQuery. It recommends thinking of widgets as small, decoupled components that communicate through events. Components should subscribe to and respond to events from other components, with references only going downward between layers. Each layer consumes events from lower layers and publishes events upward. The document also recommends decorating widget functions to add logging or other functionality.
This document provides an introduction to jQuery, covering JavaScript basics, what jQuery is, DOM manipulation with jQuery, events, animations, and additional resources. It aims to familiarize the reader with the JavaScript library jQuery and get them started with client-side scripting using the most common jQuery features and techniques. The document contains examples throughout to demonstrate jQuery concepts like selecting elements, modifying the DOM, handling events, and animations.
This document summarizes Nicholas C. Zakas's presentation on maintainable JavaScript. The presentation discusses why maintainability is important, as most time is spent maintaining code. It defines maintainable code as code that works for five years without major changes and is intuitive, understandable, adaptable, extendable, debuggable and testable. The presentation covers code style guidelines, programming practices, code organization techniques and automation tools to help write maintainable JavaScript.
Backbone.js helps structure you javascript application code in a scalable way.
In this keynote I demonstrate how to use it in a simple walk-through example, and discuss the advantages of using an MVC framework.
This document discusses using jQuery with Drupal. It provides an overview of jQuery and its benefits over JavaScript. It then discusses guidelines for using jQuery in Drupal modules and themes, such as adding JavaScript files with drupal_add_js() and defining behaviors. Examples are given of simple DOM manipulation with JavaScript, jQuery, and best practices for jQuery in Drupal.
jQuery is a JavaScript library which allows you to develop solutions with less code, in less time. You can build interactive prototypes for your prospective clients, or take an existing solution and add new dynamic behaviour with little effort.
We will see how jQuery can be used to quickly and concisely apply JavaScript behaviour to your web app. It will cover selectors, Ajax, DOM manipulation and more. The aim: to produce lean unobtrusive JavaScript with jQuery.
Getting the Most Out of jQuery Widgetsvelveeta_512
The document discusses strategies for building modular widgets in jQuery. It recommends thinking of widgets as small, decoupled components that communicate through events. Components should subscribe to and respond to events from other components, with references only going downward between layers. Each layer consumes events from lower layers and publishes events upward. The document also recommends decorating widget functions to add logging or other functionality.
This document provides an introduction to jQuery, covering JavaScript basics, what jQuery is, DOM manipulation with jQuery, events, animations, and additional resources. It aims to familiarize the reader with the JavaScript library jQuery and get them started with client-side scripting using the most common jQuery features and techniques. The document contains examples throughout to demonstrate jQuery concepts like selecting elements, modifying the DOM, handling events, and animations.
This document summarizes Nicholas C. Zakas's presentation on maintainable JavaScript. The presentation discusses why maintainability is important, as most time is spent maintaining code. It defines maintainable code as code that works for five years without major changes and is intuitive, understandable, adaptable, extendable, debuggable and testable. The presentation covers code style guidelines, programming practices, code organization techniques and automation tools to help write maintainable JavaScript.
The document introduces the jQuery library, which is a popular JavaScript library that simplifies tasks like HTML document traversal, event handling, animating, and Ajax interactions. It notes that over 20% of websites use jQuery and outlines some of its main capabilities like selecting elements, hiding/showing elements, and loading remote HTML. Alternatives to jQuery are mentioned but it is positioned as standing alone in popularity based on Google search volumes.
This document provides an introduction to jQuery, including:
- jQuery is a JavaScript library that simplifies HTML document interaction and event handling. It was created by John Resig in 2006.
- The current version is 1.3.2 and version 1.4 is coming soon. John Resig continues to develop jQuery in Boston.
- jQuery selects elements, changes their properties, handles events, and makes AJAX calls to simplify common JavaScript tasks. It works by selecting DOM elements and running functions on the selection.
This document provides an introduction to jQuery, covering its features, comparisons to other frameworks, selectors, and plugins. jQuery is an open-source JavaScript library that simplifies DOM manipulation, event handling, animations, and Ajax interactions. It uses CSS-style selectors to select and manipulate HTML elements. Some key features include DOM element selections, DOM traversal/modification, DOM manipulation based on CSS selectors, events, effects/animations, Ajax, and extensibility through plugins. The document also discusses jQuery versus other frameworks like Dojo and YUI, demonstrates basic selectors and methods, and encourages the use of plugins to add additional functionality.
jQuery is a JavaScript library that simplifies HTML document traversal, event handling, animating, and Ajax interactions. It is lightweight, cross-browser compatible, and used on over 41% of popular websites. This document provides an introduction and overview of jQuery selectors, DOM manipulation, events, effects, and Ajax capabilities in 3 sentences or less per topic.
This document provides an overview of jQuery, a JavaScript library for DOM manipulation. It discusses jQuery's CSS selector syntax, methods for manipulating DOM elements and collections, event handling, AJAX support through methods like load() and get(), and how jQuery is extensible through plugins. The document also provides examples of DOM traversal, value retrieval, event binding, and chaining methods.
This document summarizes key topics from a jQuery Brownbag presentation, including checking for null values, setting default values, properties, why jQuery is awesome, jQuery's founder and philosophy, selecting elements, events in jQuery, Ajax examples, plugins, and learning more about jQuery. The document provides code examples for common tasks like DOM manipulation, event handling, and Ajax using jQuery.
Things you should know about jQuery JavaScript library. A JavaScript library designed to hide painful cross-browser compatibility issues while presenting a solid, usable, API.
The document provides an overview of jQuery including:
- What jQuery is and its main features like DOM manipulation and AJAX
- How to include jQuery in an HTML document and basic usage syntax
- jQuery selectors to find elements and filters to refine selections
- Common jQuery methods for manipulating attributes, events, HTML, CSS, and more
- Examples of using various jQuery functions and concepts
This document outlines a presentation on jQuery fundamentals. The presentation introduces jQuery as a lightweight JavaScript library for DOM manipulation, event handling, Ajax, and animation. It covers jQuery syntax, selectors, DOM traversal and manipulation methods. It also discusses jQuery's event system, Ajax support, and plugins. The presentation includes demos of common jQuery tasks to demonstrate its usage and capabilities.
This presentation covers some jQuery basics, as well as some general concepts you should understand about jQuery. You will find other tips and tricks sprinkled throughout before the live coding session starts.
The code from the live coding session is available here: https://github.com/dcneiner/jQuery-Bling and covers far more advanced topics than the slide portion of this presentation.
The jQuery community has provided thousands of useful plugins which can be stitched together to create exceptional websites. However, organizing those plugins, tracking their upstream changes and managing dependencies can become a nightmare with a system to help you manage. JavascriptMVC, and specifically its new version 3 release, provides a framework for organizing outside code, integrating it into your workflow and compressing down to a single output javascript file. This talk will focus on taking external plugins such as jQuery Tools, jQuery UI and other popular plugins and creating a workflow for building larger applications from these components. I will show how to use the JavascriptMVC “getter” and “pluginify” scripts to pull external resources. With JavascriptMVC 3, css and javascript can be packaged together creating truly convenient widgets. I will also demonstrate how often-used pieces of functionality can be abstracted into plugins and shared with the general community via Github.
This document provides an introduction and overview of jQuery, including:
- What jQuery is and its main features for selecting, manipulating, and traversing HTML elements, handling events, animating content, and making AJAX requests.
- How jQuery works by using the jQuery() function and alias $.
- How jQuery simplifies common JavaScript tasks like selecting elements and handling events using CSS-like selectors and methods.
- Key concepts of the DOM and how jQuery interacts with and modifies the DOM.
- jQuery is a JavaScript library that simplifies HTML document traversal and manipulation, as well as event handling, animation, and Ajax.
- It works by allowing the selection of HTML elements and running functions on those elements via a simple and consistent API.
- Common uses of jQuery include modifying HTML content, CSS styling, handling user events, animating elements, and loading data from web servers via Ajax.
This document discusses jQuery, a JavaScript library. It defines jQuery as a lightweight library that allows developers to "write less, do more". It describes how jQuery works by selecting elements and running functions on them. It also covers various jQuery methods for DOM manipulation like fading, sliding, and handling events. Key points covered include selecting elements, jQuery syntax, downloading jQuery, and how to get started with basic functionality.
This document contains Simon Willison's heresies about Django. Some of the heresies discussed include that the {% if %} tags in Django templates suck, that silencing template errors is a bad idea, and that settings.py causes problems. Alternatives proposed include using a smarter {% if %} tag snippet, not silencing errors, and allowing per-application settings instead of one global settings file. The document also advocates for improving testing and documentation in the Django community.
The document discusses jQuery and its uses and methods. It introduces jQuery as a way to write JavaScript code that works across browsers. It provides examples of how jQuery can be used to select and manipulate HTML elements using simpler syntax compared to vanilla JavaScript. Key jQuery methods are also summarized, including how to select elements, modify attributes, handle events, add/move elements, and perform animations and AJAX requests.
The document is a presentation about D3 and SVG technologies. It includes sections on networking opportunities, an interactive presentation format, polls about experience levels with D3 and SVG, examples of force-directed graphs and animated SVGs using D3, and details on implementing drag and drop as well as mouseover highlighting in a D3 visualization. The presentation source code is provided on GitHub and other examples are referenced, including alternatives to SVG. It concludes with another poll and a question and answer period.
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KThomas Fuchs
The document discusses the goals and design of Zepto.js, a JavaScript framework for mobile web applications. It aims to have a very small codebase that is easy to use, extends native browser APIs, and avoids non-essential browser implementations. It provides a jQuery-like API but takes advantage of mobile features for better performance on small screens and devices with limited bandwidth.
The document provides an overview and agenda for an Advanced JavaScript course. It covers JavaScript history from 1995-1996, how JavaScript is used today both on the client-side and server-side with Node.js. It also discusses JavaScript language fundamentals like data types, objects, arrays, functions and prototypes. The agenda includes deep dives into these topics with examples and exercises to practice working with objects, arrays, functions and prototypes in JavaScript.
This document provides an overview and introduction to JavaScript. It covers the history and development of JavaScript, key concepts like its interpreter-based nature and loosely typed objects. The document outlines JavaScript's core types including numbers, strings, Booleans, null, undefined and objects. It also discusses syntax elements like identifiers, reserved words, comments, loops and branches, functions, and objects & arrays. The overall summary is that this document serves as an introductory guide to the JavaScript programming language, its core concepts and syntax.
The document introduces the jQuery library, which is a popular JavaScript library that simplifies tasks like HTML document traversal, event handling, animating, and Ajax interactions. It notes that over 20% of websites use jQuery and outlines some of its main capabilities like selecting elements, hiding/showing elements, and loading remote HTML. Alternatives to jQuery are mentioned but it is positioned as standing alone in popularity based on Google search volumes.
This document provides an introduction to jQuery, including:
- jQuery is a JavaScript library that simplifies HTML document interaction and event handling. It was created by John Resig in 2006.
- The current version is 1.3.2 and version 1.4 is coming soon. John Resig continues to develop jQuery in Boston.
- jQuery selects elements, changes their properties, handles events, and makes AJAX calls to simplify common JavaScript tasks. It works by selecting DOM elements and running functions on the selection.
This document provides an introduction to jQuery, covering its features, comparisons to other frameworks, selectors, and plugins. jQuery is an open-source JavaScript library that simplifies DOM manipulation, event handling, animations, and Ajax interactions. It uses CSS-style selectors to select and manipulate HTML elements. Some key features include DOM element selections, DOM traversal/modification, DOM manipulation based on CSS selectors, events, effects/animations, Ajax, and extensibility through plugins. The document also discusses jQuery versus other frameworks like Dojo and YUI, demonstrates basic selectors and methods, and encourages the use of plugins to add additional functionality.
jQuery is a JavaScript library that simplifies HTML document traversal, event handling, animating, and Ajax interactions. It is lightweight, cross-browser compatible, and used on over 41% of popular websites. This document provides an introduction and overview of jQuery selectors, DOM manipulation, events, effects, and Ajax capabilities in 3 sentences or less per topic.
This document provides an overview of jQuery, a JavaScript library for DOM manipulation. It discusses jQuery's CSS selector syntax, methods for manipulating DOM elements and collections, event handling, AJAX support through methods like load() and get(), and how jQuery is extensible through plugins. The document also provides examples of DOM traversal, value retrieval, event binding, and chaining methods.
This document summarizes key topics from a jQuery Brownbag presentation, including checking for null values, setting default values, properties, why jQuery is awesome, jQuery's founder and philosophy, selecting elements, events in jQuery, Ajax examples, plugins, and learning more about jQuery. The document provides code examples for common tasks like DOM manipulation, event handling, and Ajax using jQuery.
Things you should know about jQuery JavaScript library. A JavaScript library designed to hide painful cross-browser compatibility issues while presenting a solid, usable, API.
The document provides an overview of jQuery including:
- What jQuery is and its main features like DOM manipulation and AJAX
- How to include jQuery in an HTML document and basic usage syntax
- jQuery selectors to find elements and filters to refine selections
- Common jQuery methods for manipulating attributes, events, HTML, CSS, and more
- Examples of using various jQuery functions and concepts
This document outlines a presentation on jQuery fundamentals. The presentation introduces jQuery as a lightweight JavaScript library for DOM manipulation, event handling, Ajax, and animation. It covers jQuery syntax, selectors, DOM traversal and manipulation methods. It also discusses jQuery's event system, Ajax support, and plugins. The presentation includes demos of common jQuery tasks to demonstrate its usage and capabilities.
This presentation covers some jQuery basics, as well as some general concepts you should understand about jQuery. You will find other tips and tricks sprinkled throughout before the live coding session starts.
The code from the live coding session is available here: https://github.com/dcneiner/jQuery-Bling and covers far more advanced topics than the slide portion of this presentation.
The jQuery community has provided thousands of useful plugins which can be stitched together to create exceptional websites. However, organizing those plugins, tracking their upstream changes and managing dependencies can become a nightmare with a system to help you manage. JavascriptMVC, and specifically its new version 3 release, provides a framework for organizing outside code, integrating it into your workflow and compressing down to a single output javascript file. This talk will focus on taking external plugins such as jQuery Tools, jQuery UI and other popular plugins and creating a workflow for building larger applications from these components. I will show how to use the JavascriptMVC “getter” and “pluginify” scripts to pull external resources. With JavascriptMVC 3, css and javascript can be packaged together creating truly convenient widgets. I will also demonstrate how often-used pieces of functionality can be abstracted into plugins and shared with the general community via Github.
This document provides an introduction and overview of jQuery, including:
- What jQuery is and its main features for selecting, manipulating, and traversing HTML elements, handling events, animating content, and making AJAX requests.
- How jQuery works by using the jQuery() function and alias $.
- How jQuery simplifies common JavaScript tasks like selecting elements and handling events using CSS-like selectors and methods.
- Key concepts of the DOM and how jQuery interacts with and modifies the DOM.
- jQuery is a JavaScript library that simplifies HTML document traversal and manipulation, as well as event handling, animation, and Ajax.
- It works by allowing the selection of HTML elements and running functions on those elements via a simple and consistent API.
- Common uses of jQuery include modifying HTML content, CSS styling, handling user events, animating elements, and loading data from web servers via Ajax.
This document discusses jQuery, a JavaScript library. It defines jQuery as a lightweight library that allows developers to "write less, do more". It describes how jQuery works by selecting elements and running functions on them. It also covers various jQuery methods for DOM manipulation like fading, sliding, and handling events. Key points covered include selecting elements, jQuery syntax, downloading jQuery, and how to get started with basic functionality.
This document contains Simon Willison's heresies about Django. Some of the heresies discussed include that the {% if %} tags in Django templates suck, that silencing template errors is a bad idea, and that settings.py causes problems. Alternatives proposed include using a smarter {% if %} tag snippet, not silencing errors, and allowing per-application settings instead of one global settings file. The document also advocates for improving testing and documentation in the Django community.
The document discusses jQuery and its uses and methods. It introduces jQuery as a way to write JavaScript code that works across browsers. It provides examples of how jQuery can be used to select and manipulate HTML elements using simpler syntax compared to vanilla JavaScript. Key jQuery methods are also summarized, including how to select elements, modify attributes, handle events, add/move elements, and perform animations and AJAX requests.
The document is a presentation about D3 and SVG technologies. It includes sections on networking opportunities, an interactive presentation format, polls about experience levels with D3 and SVG, examples of force-directed graphs and animated SVGs using D3, and details on implementing drag and drop as well as mouseover highlighting in a D3 visualization. The presentation source code is provided on GitHub and other examples are referenced, including alternatives to SVG. It concludes with another poll and a question and answer period.
Zepto.js, a jQuery-compatible mobile JavaScript framework in 2KThomas Fuchs
The document discusses the goals and design of Zepto.js, a JavaScript framework for mobile web applications. It aims to have a very small codebase that is easy to use, extends native browser APIs, and avoids non-essential browser implementations. It provides a jQuery-like API but takes advantage of mobile features for better performance on small screens and devices with limited bandwidth.
The document provides an overview and agenda for an Advanced JavaScript course. It covers JavaScript history from 1995-1996, how JavaScript is used today both on the client-side and server-side with Node.js. It also discusses JavaScript language fundamentals like data types, objects, arrays, functions and prototypes. The agenda includes deep dives into these topics with examples and exercises to practice working with objects, arrays, functions and prototypes in JavaScript.
This document provides an overview and introduction to JavaScript. It covers the history and development of JavaScript, key concepts like its interpreter-based nature and loosely typed objects. The document outlines JavaScript's core types including numbers, strings, Booleans, null, undefined and objects. It also discusses syntax elements like identifiers, reserved words, comments, loops and branches, functions, and objects & arrays. The overall summary is that this document serves as an introductory guide to the JavaScript programming language, its core concepts and syntax.
This document provides a summary of JavaScript DOM manipulations and events. It discusses how browsers render pages by creating DOM and render trees. It also covers how JavaScript can manipulate the DOM tree and add interactivity through event handling. Key topics include the event loop, capturing vs bubbling, and the DOM API for finding elements and modifying the document.
This document provides an overview of Scalable Vector Graphics (SVG), including what SVG is, why it is useful, browser support, basic shapes and drawing, styling, animations, and scripting SVG with JavaScript. SVG is an XML-based format for describing 2D vector graphics that can be scaled to any size without loss of quality. It allows embedding graphics into web pages without using image files. The document covers the basics of drawing in SVG using simple shapes, text, paths, and gradients. It also discusses animating SVG graphics using SMIL animations and manipulating SVG dynamically with JavaScript.
This document discusses advanced CSS styling techniques including responsive design using media queries, CSS3 features such as rounded corners, shadows and gradients, CSS transitions and animations, and the Twitter Bootstrap framework. It provides examples and explanations of how to use media queries to serve different styling based on device characteristics, introduces new CSS3 features, demonstrates how to create transitions between states, and discusses keyframe animations.
The document provides an overview of HTML5 APIs, including new APIs introduced in HTML5 like Web Storage, Geolocation, Web SQL, Application Cache, Web Workers, Audio, Video, Canvas, Web Socket, Desktop Notifications, Drag & Drop, File System API, History API, and more. It discusses tools like Modernizr that can be used to detect browser support for these new APIs and polyfill missing functionality. The document also covers specific APIs in more detail, such as local storage, geolocation, offline web apps using the cache manifest, and using the Google Maps JavaScript API.
This document discusses various optimizations that can be made to improve website performance, including page load optimizations, JavaScript optimizations, and CSS optimizations. It recommends measuring and optimizing page load times, JavaScript execution, and CSS processing to enhance user experience. Specific techniques mentioned include reducing the number of HTTP requests, file sizes, and network distance as well as leveraging caching, browser parsing, and other strategies.
This document discusses various techniques for transferring data between a client and server, including JSON, web sockets, and AJAX. JSON is introduced as a widely supported format for data interchange. Web sockets allow for full-duplex communication between client and server, while AJAX can be used to make asynchronous requests. Requirements for communication protocols include wide server/client support, ease of debugging, and ability to pass firewalls. JSON meets these requirements as it is text-based, simple, and supported across many platforms. The document demonstrates using JSON to return flight data from a server to a client and discusses jQuery functions like $.get and $.ajax for making requests. It also covers concepts like the same-origin policy and techniques like JSON
This document provides an introduction and overview of web programming. It discusses the history and architecture of the web, including how HTML, CSS, and JavaScript are used on the client-side and server-side. It covers the basic structure of HTML documents and how to add common elements like text, links, images and lists. It also introduces CSS for styling HTML elements with selectors, properties and positioning. Finally, it demonstrates some popular development tools and libraries like jQuery, Kendo UI, and ExtJS that can be used to build user interfaces.
This document provides an overview of HTML5 history and features. It discusses the evolution of HTML standards from early versions to HTML5, including key events like the browser wars. It outlines the vision and rules of HTML5, such as using <!DOCTYPE html> and removing closing tags from void elements. New HTML5 features covered include semantic elements, APIs, and tools to support HTML5 development.
This document discusses JavaScript testing and provides an introduction to test-driven development (TDD) and behavior-driven development (BDD). It describes why software projects fail when code is not tested, the benefits of testing code, and demonstrates writing tests using Mocha and Expect.js for a user creation function.
Lone StarPHP 2013 - Building Web Apps from a New AnglePablo Godel
AngularJS is a new JavaScript framework, backed by Google, for building powerful, complex and rich client-side web applications. We will go over the features and basics of building a web application with AngularJS and we will demonstrate how to communitate with a REST server built with PHP.
Object-oriented programming involves creating objects that encapsulate both data (state) and behaviors (methods). Classes are templates that define objects and allow the creation of new types of objects. For example, a Point class could represent an x,y coordinate and include behaviors like translating the point and getting the distance to another point. Objects are instantiated from classes using the new keyword. Methods belong to objects to allow modifying or accessing the object's internal state.
Modeling Patterns for JavaScript Browser-Based GamesRay Toal
This document proposes JavaScript patterns for modeling browser-based game objects and types without using frameworks. It describes challenges for browser games and recent advances in JavaScript. Patterns are presented for modules, types, and inheritance using prototypes instead of classes. A root game object type and projectile subtype are implemented as examples. The patterns were applied in an HTML5 game and several JavaScript game engines are surveyed.
This document discusses JavaScript memory management and common memory leaks. It covers topics like memory lifecycle, garbage collection, detecting memory leaks using dev tools, and ways to minimize memory usage like avoiding global variables and detached DOM nodes. Common sources of memory leaks are discussed such as unbound arrays and objects, multiple copies of functions, and detached DOM nodes not removed from memory. Tools for profiling memory usage like the Chrome Task Manager and Heap Profiler are also presented.
Javascript unit testing with QUnit and SinonLars Thorup
This document discusses JavaScript unit testing with QUnit and Sinon. It introduces Lars Thorup and his background in software development, testing, and coaching. It then provides an overview of unit testing, explaining why it is beneficial and how to implement it. Finally, it demonstrates various QUnit and Sinon techniques for writing tests, including assertions, spies, stubs, mocks, asynchronous code, the DOM, and advanced mocking.
Everything is Permitted: Extending Built-insAndrew Dupont
Adding methods to built-in objects: it’s one of JavaScript’s most powerful features. It’s also a great way to offend the sensibilities of your colleagues. We all hear that it’s irresponsible, that it’s sloppy, that it’s flat-out bad practice and should be avoided.
I’m tired of this one-sided battle. In this talk, I’m going to push back against whatever blog post you read that told you that extending built-ins was unconditionally and universally bad. I’m gonna go all Howard Beale on your asses.
Value objects in JS - an ES7 work in progressBrendan Eich
This document discusses proposals for implementing value objects in JavaScript. Some key points include:
- Value objects could represent common types like integers, floats, and SIMD vectors, as well as mathematical constructs like big numbers, decimals, and complexes.
- Overloadable operators like +, -, *, / would allow defining behaviors for mathematical operations on different value object types.
- To preserve boolean identities, != and ! cannot be overloaded, and relations like > would be derived from <=.
- Strict equality operators === and !== cannot be overloaded and test structural equality.
- An approach using cacheable multimethods avoids issues with double dispatch and allows defining operators between types.
- Literal
Groovy is a dynamic language for the Java Virtual Machine that simplifies programming through features like closures, properties, and built-in support for lists, maps, ranges, and regular expressions. The latest version 1.5 adds support for Java 5 features like annotations and generics to leverage frameworks that use them. Groovy can be integrated into applications through mechanisms like JSR-223, Spring, and Groovy's own GroovyClassLoader to externalize business rules, provide extension points, and customize applications.
Testing JavaScript with Jasmine in Rails Applications Hector Correa
The document discusses using the JavaScript testing framework Jasmine to test JavaScript code. It notes issues with testing JavaScript with Ruby tools and introduces Jasmine as a solution. Key features of Jasmine highlighted include its familiar RSpec-like syntax for writing tests in JavaScript and CoffeeScript, built-in matchers for assertions, and ability to mock objects and control time. Examples are provided for testing plain JavaScript, DOM elements, using matchers and spies. Integration with continuous integration is also covered.
Back to the future with Java 7 (Geekout June/2011)Martijn Verburg
This document provides a summary of Martijn Verburg's presentation titled "Back to the Future with Java 7". The presentation covered several new features in Java 7 including Project Coin additions like strings in switch statements, try-with-resources, and diamond syntax. It also discussed NIO.2 improvements to I/O, invokedynamic, Fork/Join framework, and method handles. The presentation noted that while Java the language has been quiet, the community and platform have grown. It predicted the Java SE future looks stable while JEE and Java ME futures are less certain. The document closed with discussions on the Oracle v. Google lawsuit and the future of JavaFX.
The document discusses testing PHP code through test-driven development (TDD) and behavior-driven development (BDD). It introduces PHPUnit for writing unit tests in PHP and demonstrates writing tests before code using TDD principles. Key benefits of testing like short feedback cycles and enforcing code quality through tests are also covered. Examples of unit tests for a User class are provided to illustrate the TDD process of writing tests first, making them fail, then writing code to pass the tests.
The document discusses upcoming features in ECMAScript/JavaScript including ES6 features like arrow functions, classes, modules, and new data types. It also discusses potential future features like observable objects, SIMD intrinsics, and value objects to represent numeric types like int64 and decimal. The document proposes an approach to overloading operators for value objects using cacheable multimethods instead of double dispatch to avoid issues and maintain composability of types.
Spring Data Requery is alternatives of Spring Data JPA
Requery is lightweight ORM for DBMS (MySQL, PostgreSQL, H2, SQLite, Oracle, SQL Server)
Spring Data Requery provide Query By Native Query, Query By Example and Query By Property like Spring Data JPA
Spring Data Requery is better performance than JPA
Using Acceptance Test Driven Approach to Security Test, easy for stakeholder involvement, and a whole team approach to address security needs in software development process.
Examples in this session are based on RobotFramework, making it easy for people with limited programming skills.
This session of The Ajax Experience 2008 takes a look at the latest features in both Prototype and script.aculo.us, including custom events and how to leverage them, method wrapping for AOP-style programming, sprockets, the refactorings and improvements on Ajax, scheduling and the DOM, the new effects engine, and more.
We wrap up with an overview of the community landscape for these libraries, looking at major helpful resources, prominent peripheral frameworks, and seeing what the future looks like for both Prototype and script.aculo.us.
This document provides an overview of regular expressions (regex). It begins by stating that regex can help find patterns in text and briefly outlines the history of regex from mathematics to its introduction in Unix. It then explains that regex can be used as an alternative to shell wildcards and that many Unix tools incorporate regex. The document proceeds to list programming languages that use regex and provides some basic regex rules including matching single characters, character classes, quantifiers, and assertions. It provides examples to demonstrate matching patterns using these rules.
This document provides an overview of front-end HTML5 web development, including its history from 2004 to becoming a W3C recommendation in 2014. It discusses using new HTML5 features to build complex client-side apps and focuses on teaching attendees how to write front-end code focused on JavaScript to develop modern web applications, demonstrating examples along the way.
The document discusses various statistics related to website load times and how they impact user behavior and business metrics. It states that 47% of consumers expect a page to load within 2 seconds and 73% of mobile users have encountered sites that were too slow. A 1 second delay can result in a 7% loss in conversions. It also discusses studies by Glasses Direct, Walmart and Google on how delays of 50-400 milliseconds can negatively impact conversion rates. The document emphasizes that page load time affects bounce rates, time on site, conversions, user satisfaction and that businesses should care about and measure load times.
This document outlines a course on responsive web design for mobile. The goals are to build a responsive website that works well on any device, understand responsive tools, and learn responsive design techniques. Students should know HTML for content and CSS for styling. The course includes three mobile design challenges to complete the learning.
How to write multi threaded applications using Qt:
In the slides you'll learn about 3 alternatives, all of which allow running tasks simultaneously in Qt applications, and understand the use cases leading to choosing each.
This document discusses improving text editing for Perl developers. It outlines some annoyances with basic text editors like slowing down development. An effective text editor can help developers by providing code snippets, file templates, auto-completion and other features to reduce typing and errors. The document recommends using the Janus text editor plugin collection for Vim, which provides these kinds of features to make editing Perl code faster and easier. It provides instructions for installing Janus and highlights some of its initial capabilities.
This 24-hour course covers the architectural differences system analysts must consider when designing mobile or mobile web applications. It discusses topics like the mobile ecosystem, application layers, device layers, communication networks, and security. The course will help participants understand how to manage sessions, use location services, send push notifications, optimize for networks and address vulnerabilities, through in-depth topics, real-world case studies and a suggested 6-session schedule.
The document discusses key differences between developing for mobile versus desktop. Mobile devices are always connected, have limited battery life, and users expect seamless app switching. Developers must consider interruptions and optimize for battery usage. Each mobile app runs in a sandbox and can communicate through URL schemes or by integrating with OS services. Background execution is more limited on iOS but both platforms allow some background activities like downloading content or playing audio. Developers must respect user expectations and not abuse background capabilities.
This document discusses optimizing mobile networks and applications for speed. It begins with an overview of networking basics and how mobile networks work. It then discusses factors that affect speed like latency, bandwidth, TCP protocols, and cellular network routing. The document provides recommendations for optimizing like leveraging WiFi, anticipating latency, saving bandwidth and battery. It also covers HTTP optimizations, browser APIs and protocols like XHR, SSE and WebSockets. The goal is to understand how networks impact applications and how to design for optimal mobile performance.
The document discusses mobile web architecture and hybrid mobile applications. It begins with an introduction to hybrid apps and PhoneGap. It then covers various HTML5 features that are useful for building hybrid apps like users and sessions, location services, cameras, videos, audio and push notifications. It explains the hybrid architecture of combining web views with native wrappers. It also provides examples of implementing location services, cameras, audio/video and push notifications in a hybrid mobile app.
This document discusses misusing cryptography. It begins with an agenda covering why cryptography is misused and how random number generators and crypto algorithms can be misused. It then discusses examples of what can go wrong, such as a game developer unintentionally allowing hackers to easily determine the secret code protecting scores. The document emphasizes that cryptography is complex and should not be casually misused, as failures can result in compromises like hacked systems and lost jobs. It provides recommendations for proper cryptographic practices.
This document provides an introduction to Selenium, an open source tool for automating web application testing. Selenium allows testing of web applications across different browsers without needing to modify the source code. It works by issuing commands to browser drivers to simulate user interactions such as clicking links, filling forms, and verifying page content. The document outlines how to set up and run automated tests using the Selenium Ruby bindings and RSpec testing framework.
Slides cover how to get started testing your web application. Technologies and concepts explained:
- Unit tests (mocha, jasmine, karma)
- System tests (Selenium)
- Code coverage (istanbul)
- CI servers
This document discusses web accessibility and provides guidance on making websites accessible to people with disabilities. It covers goals of accessibility, challenges for different disabilities, relevant laws, and technical details on how to make elements like images, audio, video, forms, tables, and overall site structure and navigation accessible. The document provides guidelines on topics like alt text, captions, text size and color contrast, keyboard navigation, time limits, languages, and using semantic HTML.
The document provides an overview and introduction to AngularJS. It discusses key Angular concepts like data binding, directives, filters, controllers and scopes. It also covers using Angular for client-side routing and communicating with servers to retrieve data. Example code snippets are provided to demonstrate concepts like controllers, directives and routing. Labs and exercises are included to apply the concepts by building sample Angular applications.
Design Patterns help us solve problems in tried and tested ways.
Turns out they also help us understand our framework better, for framework developers also use patterns.
In these slides you'll see how Design Patterns are implemented by Qt framework, to better both understand patterns and Qt
This document provides an overview and introduction to getting started with MongoDB. It discusses that MongoDB is a document-oriented database that stores JSON-like documents with dynamic schemas. It can be used to create and store JSON objects and arrange them in collections. The document outlines several MongoDB concepts including its data model, CRUD operations using queries and operators, and working with embedded documents and arrays. It also provides an agenda for a presentation on using MongoDB with topics like schemas, querying, validation, and plugins.
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
GraphSummit Singapore | The Art of the Possible with Graph - Q2 2024Neo4j
Neha Bajwa, Vice President of Product Marketing, Neo4j
Join us as we explore breakthrough innovations enabled by interconnected data and AI. Discover firsthand how organizations use relationships in data to uncover contextual insights and solve our most pressing challenges – from optimizing supply chains, detecting fraud, and improving customer experiences to accelerating drug discoveries.
How to Get CNIC Information System with Paksim Ga.pptxdanishmna97
Pakdata Cf is a groundbreaking system designed to streamline and facilitate access to CNIC information. This innovative platform leverages advanced technology to provide users with efficient and secure access to their CNIC details.
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Speck&Tech
ABSTRACT: A prima vista, un mattoncino Lego e la backdoor XZ potrebbero avere in comune il fatto di essere entrambi blocchi di costruzione, o dipendenze di progetti creativi e software. La realtà è che un mattoncino Lego e il caso della backdoor XZ hanno molto di più di tutto ciò in comune.
Partecipate alla presentazione per immergervi in una storia di interoperabilità, standard e formati aperti, per poi discutere del ruolo importante che i contributori hanno in una comunità open source sostenibile.
BIO: Sostenitrice del software libero e dei formati standard e aperti. È stata un membro attivo dei progetti Fedora e openSUSE e ha co-fondato l'Associazione LibreItalia dove è stata coinvolta in diversi eventi, migrazioni e formazione relativi a LibreOffice. In precedenza ha lavorato a migrazioni e corsi di formazione su LibreOffice per diverse amministrazioni pubbliche e privati. Da gennaio 2020 lavora in SUSE come Software Release Engineer per Uyuni e SUSE Manager e quando non segue la sua passione per i computer e per Geeko coltiva la sua curiosità per l'astronomia (da cui deriva il suo nickname deneb_alpha).
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
Enchancing adoption of Open Source Libraries. A case study on Albumentations.AIVladimir Iglovikov, Ph.D.
Presented by Vladimir Iglovikov:
- https://www.linkedin.com/in/iglovikov/
- https://x.com/viglovikov
- https://www.instagram.com/ternaus/
This presentation delves into the journey of Albumentations.ai, a highly successful open-source library for data augmentation.
Created out of a necessity for superior performance in Kaggle competitions, Albumentations has grown to become a widely used tool among data scientists and machine learning practitioners.
This case study covers various aspects, including:
People: The contributors and community that have supported Albumentations.
Metrics: The success indicators such as downloads, daily active users, GitHub stars, and financial contributions.
Challenges: The hurdles in monetizing open-source projects and measuring user engagement.
Development Practices: Best practices for creating, maintaining, and scaling open-source libraries, including code hygiene, CI/CD, and fast iteration.
Community Building: Strategies for making adoption easy, iterating quickly, and fostering a vibrant, engaged community.
Marketing: Both online and offline marketing tactics, focusing on real, impactful interactions and collaborations.
Mental Health: Maintaining balance and not feeling pressured by user demands.
Key insights include the importance of automation, making the adoption process seamless, and leveraging offline interactions for marketing. The presentation also emphasizes the need for continuous small improvements and building a friendly, inclusive community that contributes to the project's growth.
Vladimir Iglovikov brings his extensive experience as a Kaggle Grandmaster, ex-Staff ML Engineer at Lyft, sharing valuable lessons and practical advice for anyone looking to enhance the adoption of their open-source projects.
Explore more about Albumentations and join the community at:
GitHub: https://github.com/albumentations-team/albumentations
Website: https://albumentations.ai/
LinkedIn: https://www.linkedin.com/company/100504475
Twitter: https://x.com/albumentations
Goodbye Windows 11: Make Way for Nitrux Linux 3.5.0!SOFTTECHHUB
As the digital landscape continually evolves, operating systems play a critical role in shaping user experiences and productivity. The launch of Nitrux Linux 3.5.0 marks a significant milestone, offering a robust alternative to traditional systems such as Windows 11. This article delves into the essence of Nitrux Linux 3.5.0, exploring its unique features, advantages, and how it stands as a compelling choice for both casual users and tech enthusiasts.
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Sudheer Mechineni, Head of Application Frameworks, Standard Chartered Bank
Discover how Standard Chartered Bank harnessed the power of Neo4j to transform complex data access challenges into a dynamic, scalable graph database solution. This keynote will cover their journey from initial adoption to deploying a fully automated, enterprise-grade causal cluster, highlighting key strategies for modelling organisational changes and ensuring robust disaster recovery. Learn how these innovations have not only enhanced Standard Chartered Bank’s data infrastructure but also positioned them as pioneers in the banking sector’s adoption of graph technology.
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfMalak Abu Hammad
Discover how MongoDB Atlas and vector search technology can revolutionize your application's search capabilities. This comprehensive presentation covers:
* What is Vector Search?
* Importance and benefits of vector search
* Practical use cases across various industries
* Step-by-step implementation guide
* Live demos with code snippets
* Enhancing LLM capabilities with vector search
* Best practices and optimization strategies
Perfect for developers, AI enthusiasts, and tech leaders. Learn how to leverage MongoDB Atlas to deliver highly relevant, context-aware search results, transforming your data retrieval process. Stay ahead in tech innovation and maximize the potential of your applications.
#MongoDB #VectorSearch #AI #SemanticSearch #TechInnovation #DataScience #LLM #MachineLearning #SearchTechnology
TrustArc Webinar - 2024 Global Privacy SurveyTrustArc
How does your privacy program stack up against your peers? What challenges are privacy teams tackling and prioritizing in 2024?
In the fifth annual Global Privacy Benchmarks Survey, we asked over 1,800 global privacy professionals and business executives to share their perspectives on the current state of privacy inside and outside of their organizations. This year’s report focused on emerging areas of importance for privacy and compliance professionals, including considerations and implications of Artificial Intelligence (AI) technologies, building brand trust, and different approaches for achieving higher privacy competence scores.
See how organizational priorities and strategic approaches to data security and privacy are evolving around the globe.
This webinar will review:
- The top 10 privacy insights from the fifth annual Global Privacy Benchmarks Survey
- The top challenges for privacy leaders, practitioners, and organizations in 2024
- Key themes to consider in developing and maintaining your privacy program
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
3. Agenda
• JavaScript Short History
• Code Architecture For An App
• Module Pattern
• Memory Management Pitfalls
Monday, January 28, 13
4. History
• 1995 Bredan Eich started
developing a new language for
Netscape Navigator 2.0
• Original name was LiveScript
• Renamed to JavaScript Dec
that year
• 1996 MS responded with
JScript
• Nov 1996 - Netscape submits
JavaScript to ECMA
Monday, January 28, 13
5. State Of JavaScript
• Used for frontend web based
development for desktop and
mobile
• Used for server side
development using Node.JS
• Embedded in desktop
applications using various JS
interpreters
• Used in Windows 8 to write
apps
Monday, January 28, 13
6. Key Concepts In JavaScript
• It’s interpreter based (though engines are highly optimized)
• It’s loosely typed
• Objects are just hash tables
• Look Ma, OO Without Classes
• Prototypical Inheritance
Monday, January 28, 13
7. JavaScript Objects
• Objects are containers for data
and functions
• They hold key/value pairs
• key is a string (or else it is
stringified)
• value can be anything
name Ynon Perek
website
http://
www.ynonperek.com
Monday, January 28, 13
8. JavaScript Objects
• Define an object with {...}
• Add key/value pair by assigning
to it
• Remove key/value pair with
delete
• Print an object with
console.dir(...)
• Try not to change them too
often
var me = {
name: 'ynon',
email: 'ynon@ynonperek.com'
};
me.web = 'ynonperek.com';
delete me.web;
var key = 'likes';
me[key] = 'JavaScript';
console.dir( me );
Monday, January 28, 13
9. JavaScript Objects Quiz
• What Happens Here ?
var o = {};
o[0] = 5;
o['0'] = 7;
console.log(o[0]);
Monday, January 28, 13
10. JavaScript Objects Quiz
• 7 is printed.
• Remember, keys are stringified
var o = {};
o[0] = 5;
o['0'] = 7;
console.log(o[0]);
Monday, January 28, 13
11. new Object(...) Quiz
• What Is Printed Here:
var a = { foo: 7 };
var b = new Object('foo', 7);
var c = new Object(1, 2, 3);
var d = new Object([1,2,3]);
var e = new Object({'foo' : 7});
console.dir( a );
console.dir( b );
console.dir( c );
console.dir( d );
console.dir( e );
Monday, January 28, 13
12. new Object(...) Quiz
• What Is Printed Here:
// { foo: 7 }
console.dir( a );
// { '0': 'f', '1': 'o', '2': 'o' }
console.dir( b );
// {}
console.dir( c );
// [1, 2, 3]
console.dir( d );
// { foo: 7 }
console.dir( e );
var a = { foo: 7 };
var b = new Object('foo', 7);
var c = new Object(1, 2, 3);
var d = new Object([1,2,3]);
var e = new Object({'foo' : 7});
Monday, January 28, 13
15. Classes are important
• They make it easy to create new objects
• They make it less error prone
• They help JavaScript engines optimize
• They make our code readable
Monday, January 28, 13
16. Maker Functions as classes: Take #1
• Works, but not scalable
function Person(name, age) {
this.hello = function() {
console.log( name );
};
}
var p = new Person('Jim', 12);
p.hello();
Monday, January 28, 13
17. Maker Functions as classes: Take #1
• What happens here ?
function Person(name, age) {
this.met = 0;
this.hello = function() {
this.met += 1;
console.log( name + ' Met ' + this.met + ' people' );
};
}
var p = new Person('Jim', 12);
p.hello();
setTimeout( p.hello, 10 );
Monday, January 28, 13
18. JavaScript Objects Gotchas
• Methods are bound on invocation and not on declaration.
• Only closures are bound on declaration.
• Solution: Replace this with closures.
Monday, January 28, 13
19. Maker Functions as classes: Take #2
function Person(name, age) {
var self = this;
self.met = 0;
self.hello = function() {
self.met += 1;
console.log( name + ' Met ' + self.met + ' people' );
};
}
var p = new Person('Jim', 12);
p.hello();
setTimeout( p.hello, 10 );
Monday, January 28, 13
21. Prototype Chain
Person
age : 12
Student
grade : 90
Freshman
goto: party
Worker
salary : 3800
Freshman.grade === 90 // from Student
Student.age === 12 // from Person
Worker.age === 12 // from Person
Worker.salary === 3800 // from Worker
Monday, January 28, 13
22. Prototype Chain
• Every JavaScrip Object has a prototype
• When the JS interpreter fails to find a property in the object, it searches the
prototype
• A prototype can also have its own prototype, that’s why we call it a chain
• Define A Prototype by assigning value to the .prototype key in the maker
function
• Tip: Use prototypes for functions, not for data
Monday, January 28, 13
23. Demo: Defining A Prototype without Data
var PersonPrototype = {
hi: function() {
console.log('Hi ! ');
}
};
function Student(age, gradesArray) {
...
}
Student.prototype = PersonPrototype;
var me = new Student(20, [90, 80, 70, 80]);
console.log( me.grade() );
// Works from the prototype
me.hi();
Monday, January 28, 13
24. Prototype and Class Interaction
• Since methods are bound on invocation, inside the prototype this usually
refers to the child object
• Use this to add data to the original object
• Use this to read data from the original object
• Never store data on the prototype itself (it’ll be shared).
Monday, January 28, 13
25. Demo: Prototype and Class Interaction
var PersonPrototype = {
_age: 0,
hi: function() {
console.log('Hi ! ' + this._age);
},
grow_up: function() {
this._age += 1;
}
};
// Works from the prototype
me.hi();
me.grow_up();
me.hi();
console.log('Me: ');
console.dir( me );
console.log('Prototype: ');
console.dir( PersonPrototype );
Monday, January 28, 13
26. Prototypes: Common Pitfalls
• Don’t use closures when defining prototypes.
• This will save the data on the prototype object.
• The data is then shared between all objects using the same prototype.
Monday, January 28, 13
27. Prototypes Lab
• Write a Maker Function for a Car object. Car should provide max_speed()
and drive() functions.
• Write maker functions for 3 car models (Mitsubishi, BMW and Mazda). Use
Car as their prototype. Make sure max_speed returns the correct value for
each model.
• Add a Race class which takes multiple cars from different models, and prints
out which is the fastest.
Monday, January 28, 13
28. Code Architecture
For An App
Avoiding Global Objects
Using Namespaces
Using Single Var Statement
Monday, January 28, 13
29. JavaScript Bad Choice
• By default, all variables are global
• By global - we mean properties of the global object
Global
Object
function foo
function bar
number n
String name
Monday, January 28, 13
30. Variable Scoping Options
• A Variable can be defined either on the global object, or on a function object
• To define a lexical function variable, use the keyword var inside a function
function foo() {
var n = 5;
var m = 8;
}
Monday, January 28, 13
31. What’s Wrong With Globals
• Bad Programming Style
• Globals make it hard to write and use libraries
• Globals are never garbage-collected
Monday, January 28, 13
32. Eliminating Globals Is Hard
var main = function() {
var x = 5, y = 7;
for ( var i=0; i < 10; i++ ) {
console.log( x + y );
x += y;
}
};
main();
Monday, January 28, 13
33. But It’s Possible
(function() {
var x = 5, y = 7;
for ( var i=0; i < 10; i++ ) {
console.log( x + y );
x += y;
}
}());
Monday, January 28, 13
34. When Globals Are Inescapable
• Define and use a namespace
• Define classes (Make functions)
• You’ll need a global to share data between code written in multiple files
• Demo: Using Globals
Monday, January 28, 13
35. What’s Variable Hoisting And Why You Should Care
• JavaScript can only create variables as attributes of objects
• In global scope, they’re attributes of the global object
• In function scope, they’re attributes of the function calling object
• Since variables are not lexically scopes, some interesting bugs arise
Monday, January 28, 13
37. Possible Workaround
• Avoid using multiple var statements inside a function
• It won’t prevent the bug, but at least it’ll be easier to spot
• Remember: Only functions have variables
Monday, January 28, 13
41. Disadvantages Of Script Tags
• No Hierarchy in modules
• No optional modules
• Slower code loading (Need to wait for EVERYTHING to load)
• Too many globals
Monday, January 28, 13
44. Hello Require.JS - Defining A Module
// book.js
define(function() {
return function(title, author) {
this.title = title;
this.author = author;
this.year = new Date().getUTCFullYear();
};
});
Note the return value
of the callback define takes
Monday, January 28, 13
45. Hello Require.JS - Using A Module
// main.js
define(['book'], function(Book) {
var foo = new Book('JS Rocks', 'Jim');
console.dir( foo );
});
Monday, January 28, 13
46. Hello Require.JS - Using A Module
// main.js
define(['book'], function(Book) {
var foo = new Book('JS Rocks', 'Jim');
console.dir( foo );
});
Define can take an array of dependencies as its first
argument. It’ll call the callback passing each module
as argument
return value of book.js
Monday, January 28, 13
47. Require and Browser Cache
• By default require instructs the browser to cache all modules
• For development, you can override it by setting urlArgs
• For production, add a constant version value
<script>
require.config({
urlArgs: "bust=" + new Date().getTime()
});
</script>
Monday, January 28, 13
48. What We Got From Require.JS
• No need for global variables or namespaces
• JavaScript files can declare dependencies between each other
• No need to manually set <script> tags order
Monday, January 28, 13
50. Defining Modules
• Use define({...}) to define an object that has no dependencies
//Inside file my/shirt.js:
define({
color: "black",
size: "unisize"
});
Monday, January 28, 13
51. Defining Modules With Initialization Code
• Use define(function() { ... } ) to define a module that has initialization code
• Example:
//my/shirt.js now does setup work
//before returning its module definition.
define(function () {
//Do setup work here
return {
color: "black",
size: "unisize"
}
});
Monday, January 28, 13
52. Defining A Module With Dependencies
• Use define([array], function(...) {}) to define a module with dependencies
• All dependencies will be loaded async, and then your callback function is
invoked, with all dependencies as arguments
Monday, January 28, 13
53. Defining A Module With Dependencies
• Example:
//my/shirt.js now has some dependencies, a cart and inventory
//module in the same directory as shirt.js
define(["./cart", "./inventory"], function(cart, inventory) {
//return an object to define the "my/shirt" module.
return {
color: "blue",
size: "large",
addToCart: function() {
inventory.decrement(this);
cart.add(this);
}
}
}
);
Monday, January 28, 13
54. Using Maker Functions As Modules
• define’s callback’s return value can be anything
• Returning a Maker Function from the callback results in a “Class”
• Usage:
define(['book'], function(Book) {
var book = new Book();
});
Monday, January 28, 13
55. Modules Notes
• Define only one module per file
• Don’t do circular dependencies (but if you must, here’s how to do it right:
http://requirejs.org/docs/api.html#circular)
• Modules are loaded by adding <script> tags to head (head.appendChild()).
Monday, January 28, 13
57. Supported Options
• baseUrl: Root path to use for all modules lookup. Defaults to the path of the
main script, or the location of containing HTML.
• shim: allow using require(...) on old modules by telling require how they work.
Example:
shim: {
'backbone': {
deps: ['underscore', 'jquery'],
//Once loaded, use the global 'Backbone' as the
//module value.
exports: 'Backbone'
},
Monday, January 28, 13
58. Supported Options
• waitSeconds: timeout to wait for a module. Defaults to 7.
If set to 0, waits forever.
• enforceDefine: throws an error if trying to load a script that’s not AMD nor
defined in a shim
• urlArgs: extra query string data (useful to disable cache)
Monday, January 28, 13
59. Demo: Using Vendor Libraries
• Use require config to include vendor libraries from a CDN
• You can even pass an array to provide local fallback
requirejs.config({
paths: {
jquery: [
'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/
jquery.min',
//If the CDN location fails, load from this location
'lib/jquery'
]
}
});
Monday, January 28, 13
60. Handling Errors
• Define a global requirejs.onError function to handle errors
• Function takes two arguments: error object and (optional) modules array
requirejs.onError = function(etype, emod) {
console.log('error');
console.dir( etype );
console.dir( emod );
}
Monday, January 28, 13
62. Require.JS Lab
• Write a Quiz App:
• A Common Question Prototype Module
• A Module for Multiple Choice Question
• A Module for scale (1-5) question
• A Module for the Quiz (has an array of questions)
• Use Require.JS to load them
Monday, January 28, 13
64. Memory Lifecycle
• All languages are the same:
• (1) Allocate some memory
• (2) Use that memory
• (3) Free that memory
• In JS, #3 is implicit
Monday, January 28, 13
65. Memory Is Allocated When You Define Literals
var n = 123;
var s = "azerty";
var o = {
a: 1,
b: null
};
var a = [1, null, "abra"];
function f(a){
return a + 2;
}
someElement.addEventListener('click', function(){
someElement.style.backgroundColor = 'blue';
}, false);
Monday, January 28, 13
66. Hidden Memory Allocations
var d = new Date();
var e = document.createElement('div'); // allocates an DOM
element
var s = "foo";
var s2 = s.substr(0, 3); // s2 is a new string
var a = ["ouais ouais", "nan nan"];
var a2 = ["generation", "nan nan"];
var a3 = a.concat(a2);
Monday, January 28, 13
67. Releasing Memory
• JavaScript uses Mark-And-Sweep garbage collection algorithm
• It starts from known memory (global object)
• Follows all references
• In the end, clear the unreachable
Monday, January 28, 13
72. Cleaning Up Memory
• Avoid global variables
• A global is NEVER freed
• A lexical is freed when out-of-scope
• Limit cache sizes
• Don’t use old IE (6-7)
Monday, January 28, 13
73. Common Leak: Hanging Detached Nodes
<button>Click Me</button>
<div>10</div>
<script>
var btn = document.querySelector('button');
var counter = 10;
var div = document.querySelector('div');
btn.addEventListener('click', function() {
if ( counter < 0 ) return;
counter -= 1;
div.innerHTML = counter;
if ( counter == 0 ) {
div.parentElement.removeChild(div);
}
});
</script>
Monday, January 28, 13
74. Fix By Using Lexicals
<button>Click Me</button>
<div>10</div>
<script>
var btn = document.querySelector('button');
var counter = 10;
btn.addEventListener('click', function() {
var div = document.querySelector('div');
if ( counter < 0 ) return;
counter -= 1;
div.innerHTML = counter;
if ( counter == 0 ) {
div.parentElement.removeChild(div);
}
});
</script>
Monday, January 28, 13
75. Common Leak: Unlimited Cache Size
var cache = {};
var fib = function(n) {
if ( ! cache[n] ) {
if ( n < 2 ) {
cache[n] = 1
} else {
cache[n] = fib(n-1) + fib(n-2);
}
}
return cache[n];
};
Monday, January 28, 13
76. Fix: Smart Caching
• Define Cache() class to take
size limit on ctor (or use default)
• Cache.add should check if has
enough space, or remove old
elements
• Bonus: play with keep/remove
strategies to reach maximum
performance
var cache = new Cache(10);
var fib = function(n) {
if ( ! cache[n] ) {
if ( n < 2 ) {
cache.add(n, 1 );
} else {
cache.add(n, fib(n-1) + fib(n-2) );
}
}
return cache.get(n);
};
Monday, January 28, 13
77. Common Error: Keeping Multiple Function Copies
• Each function takes space in
memory
• A constructor that puts
functions directly on the object
makes the object larger
• Many objects that share the
same function are a waste
var Person = function() {
var self = this;
self.hi = function() {
console.log('Hello World!');
};
self.grow_up = function() {
self.age += 1;
};
self.age = 0;
};
Monday, January 28, 13
78. Fix: Use Prototypes
• Functions are defined in
prototypes
• Data is defined in object
• Use bind when you need to use
a function as an event handler
• Note: Can hurt readability
var PersonActions = {
hi: function() {
console.log('Hello World!');
},
grow_up: function() {
this.age += 1;
}
};
Person.prototype = PersonActions;
Monday, January 28, 13
79. Tools For Memory Management
• Chrome Task Manager,
available from:
• Tools->Task Manager
• If memory tab is hidden, turn it
on via context menu
Monday, January 28, 13
80. Tools For Memory Management
• Chrome Memory Timeline
• Available from Developer Tools
Monday, January 28, 13
81. Tools For Memory Management
• Chrome Heap Profiler
• Available from Developer Tools
Monday, January 28, 13