Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

DOM

No description
by

Juan Pablo Francisconi

on 3 June 2015

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of DOM

DOM *W3C Standard
(1) Data Binding
DOM 1.0 - limited mutability
DOM 2.0 - full mutability
DOM 3.0+ - manipulation of child elements
A structural representation a la tree of objects that represents the HTML document.
A standard programming interface for HTML (API) - how to get, change, add, or delete HTML elements.
Allows you to view and modify page elements in script code after page has loaded.
What it is?
Evolution
1
2
3
4
DOM Events
Event setup
(1)
Calculate parent node path
(2)
Execute Capture Phase handlers
(3)
Execute DOM Level 1 event handler
(4)
Execute Bubble Phase handlers
(5)
Execute default browser behavior
(6)
DOM events traverse the document in the bubble and capture phase
The order the event traverses the parent chain is determined before any event handlers are fired
Steps
Conclusion
AngularJS
AngularJS is a JavaScript framework which simplifies binding JavaScript objects with HTML UI elements
History
Angular’s beginnings goes back to 2009, on a project called Google Feedback. It looks like it came out after months of frustration with the development speed, inability to write testable and maintainable code and around 17,000 lines of front-end code. Misko Hevery re-wrote the whole thing and dropped
the number of lines to 1,500.
Concepts
Client-Side Templates:
template and data get shipped to the browser to be assembled there
Two-Way Data Binding:
declare which parts of the UI map to which JavaScript properties and have them sync auto
Dependency Injection:
one particular component does not directly create references to other components
Directives:
markers on a DOM element which attach a special behavior to it
function
UiToObject
() {
Cust.CustomerName = $("#TxtCustomerName").val();
}
function
ObjectToUi
() {
$("#TxtCustomerName").val(Cust.CustomerName);
}
<div ng-controller="Customer">
<input type=text id="txtCustomerName"
ng-model
="CustomerName"/>
</div>
<input type=text id="TxtCustomerName"
onchange
="UiToObject()"/>
function
Customer
() {
this.CustomerName = "AngularJS";
}
var Cust = new Customer();
HTML
JS
Data Binding
JQuery
Angular
HTML
JS
function Customer($scope) {

$scope
.CustomerName = "AngularJS";
}
Data Binding
Controller - $scope
A
controller
is a simple JS function which provides data and logic to the UI. It controls how data flows from the server to UI
The
$scope
is an object instance of a controller. “$scope” object instance get’s created when “ng-controller” directive is encountered.
$rootScope
The
$rootScope
is a parent object of all “$scope” angular objects created in a web page.
Two Way Data Binding
1 - When properties in the
model
get updated, so does the
UI
.

2 - When
UI
elements get updated, the changes get propagated back to the
model
.
it makes the
model
abstraction a safe, atomic data source to use everywhere within the application
Phases
Step 1:
- HTML browser parses the HTML and creates a DOM (Document Object Model).

Step 2:
- Angular framework runs over this DOM looks at the Angular directives and manipulates the DOM accordingly.

Step 3:
- This manipulated is then rendered as HTML in the browser.
Compile:
traverse the DOM and collect all directives. The result is a liking function.


Link:
combine directives with the scope and produce a live view.
Compile - Link
After compilinig (enable all directives and attaching models to $scope and create the watch list -
$watch
) we obtain a
live view
. The live view is watched and updated by
$digest
(event loop)
(2) Directives
Directives
are markers on a DOM element which attach a
special
behavior to it
(2) Directives
Types of custom directives:
1 - Element directives (E)
2 - Attribute directives (A)
3 - CSS class directives (C)
4 - Comment directives (M)
myapp.directive('
userinfo'
, function() {
var directive = {};
directive.restrict = 'E';
directive.template = "User :
{{user.firstName}} {{user.lastName}}
";
return directie;
});
<userinfo></userinfo>
Element level
(works)
:
Attribute level
(doesn't work)
:
<div
userinfo
></div>
(3) Dependency Injection
(4) Templates
Summary
Best Practices - 1) Structure
These
core types
can be injected into each other using AngularJS dependency injection mechanism:

Value
Factory
Service
Provider
Constant
var
myUtilModule
= angular.module("myUtilModule", []);
myUtilModule.value (
"myValue"
, "12345");

----
var
myOtherModule
= angular.module("myOtherModule", [
'myUtilModule'
]);
----
myOtherModule.controller("MyController", function($scope,
myValue
) {}
Angular is different in that the template and data get shipped to the browser to be
assembled
there
The role of the server then becomes only to
serve as static resources
for the templates and to
properly serve the data
required by those templates
{{hello.text}}, World
function MyHelloController($scope) {
$scope.hello = { text: 'Hello' };
}

1) HTML
2) MODEL
app/
----- shared/
// acts as reusable components or partials of our site
---------- sidebar/
--------------- sidebarDirective.js
--------------- sidebarView.html
---------- article/
--------------- articleDirective.js
--------------- articleView.html
----- components/
// each component is treated as a mini Angular app
---------- home/
--------------- homeController.js
--------------- homeService.js
--------------- homeView.html
---------- blog/
--------------- blogController.js
--------------- blogService.js
--------------- blogView.html
----- app.module.js
----- app.routes.js
assets/
----- img/
// Images and icons for your app
----- css/
// All styles and style related files (SCSS or LESS files)
----- js/
// JavaScript files written for your app that are not for angular
----- libs/
// Third-party libraries such as jQuery, Moment, Underscore, etc.
index.html
app/
----- controllers/
---------- mainController.js
---------- otherController.js
----- directives/
---------- mainDirective.js
---------- otherDirective.js
----- services/
---------- userService.js
---------- itemService.js
----- js/
---------- bootstrap.js
---------- jquery.js
----- app.js
views/
----- mainView.html
----- otherView.html
----- index.html
vs
Traditional
Recommended
Best Practices - 2) Constants
'use strict';
angular
.module('abp001App', ['ngRoute'])

.constant(
"myConfig", {
"url": "http://localhost",
"port": "80"
})
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/main.html',
controller: 'MainCtrl'
})
.otherwise({
redirectTo: '/'
});
})
.controller('MainCtrl', function (myConfig) {
// Do something with myConfig...
});

Think that a constant should be something that you
can’t modify
even with a decorator
constant(name, value);
A constant could be a
string
, a
number
, an
array
, an
object
or a
function
.
Creating high-level divisions by functionality and lower-level divisions by component types
Best Practices - 3) Markup
Put the scripts at the bottom.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>MyApp</title>
</head>
<body>
<div ng-app="myApp">
<div ng-view></div>
</div>

<script src="angular.js"></script>
<script src="app.js"></script>
</body>
</html>
Keep things simple and put AngularJS specific directives later. This way is easy to look to the code and find enhanced HTML by the framework (what improve the maintainibility)
<form class="frm" ng-submit="login.authenticate()">
<div>
<input class="ipt" type="text" placeholder="name" require
ng-model=
"user.name">
</div>
</form>
Best Practices - 4) Modules
1) Modules should be named with
lowerCamelCase
. For indicating that module
b
is submodule of module
a
you can
nest
them by using namespacing like:
a.b
.

angular.module('demoPresentation', [])

2) Ways for
structuring
the modules:

a)
By functionality
b)
By component type

Currently there's not a big difference, but the first way looks
cleaner
.
Best Practices - 5) Controllers
1 - Do not manipulate
DOM
in your controllers. Use
directives
instead.
2 - The naming of the controller is done using the
controller's functionality
.
3 - Controllers are plain javascript constructors, so they will be named
UpperCamelCase
.
4 - The controllers should not be defined as
globals
.
5 - Use the following syntax:
function
MyCtrl
(dependency1, dependency2, ..., dependencyn) {
// ...
}
module.controller('MyCtrl',
MyCtrl
);
6 -
Avoid
writing
business logic
inside controllers. Delegate business logic to a model.
7 - Communicate within different controllers using method invocation or
$emit
,
$broadcast
and
$on
methods.
8 - When you need to format data encapsulate the formatting logic into a
filter
and declare it as
dependency
Best Practices - 5) Directives
1 - Name your directives with
lowerCamelCase
.

2 - Use
custom prefixes
for your directives to prevent name
collisions
with third-party libraries.

3 -
Do not
use
ng
or
ui
prefixes since they are
reserved
for AngularJS and AngularJS UI usage.

4 - DOM manipulations must be done only through directives.

5 - Use directives as
attributes
or
elements
instead of comments or classes, this will make your code more readable.

Best Practices - 6) Services
1 - Use
camelCase
to name your services.
2 - Encapsulate all the business logic in services:
//Order is the 'model'
angular.module('Store').factory('Order', function () {
var
add
= function (item) {
this.items.push (item);
};
var
remove
= function (item) {
if (this.items.indexOf(item) > -1) {
this.items.splice(this.items.indexOf(item), 1);
}
};
var
total
= function () {
return this.items.reduce(function (memo, item) {
return memo + (item.qty * item.price);
}, 0);
};

return
{
items: [],
addToOrder: add,
removeFromOrder: remove,
totalPrice: total
};
});
3 - For session-level cache you can use
$cacheFactory
. This should be used to cache results from requests or heavy computations.
4 - Services representing the
domain
preferably use a service instead of a factory.
5 - If given service requires configuration
define the service as provider
and configure it in the config callback
Best Practices - 7) Templates
1 -
Avoid
writing
complex expressions
in the templates

2 - When you need to set the src of an image dynamically use
ng-src
instead of src with {{ }} template.

3 - When you need to set the href of an anchor tag dynamically use
ng-href
instead of href with {{ }} template.

4 - Use
ng-bind
or
ng-cloak
instead of simple {{ }} to prevent flashing content.

5 - Instead of using scope variable as string and using it with style attribute with {{ }}, use the directive
ng-style
.
Best Practices - 7) Performance
1) Use:
$timeout
instead of setTimeout
$interval
instead of setInterval
$window
instead of window
$document
instead of document
$http
instead of $.ajax
Best Practices - 8) Others
2) Automate your workflow using tools like:
Yeoman
,
Gulp
,
Grunt
or
Bower
3) Use promises (
$q
) instead of callbacks.
4) Use
$resource
instead of
$http
when possible. The higher level of abstraction will save you from redundancy
5)
Do not pollute
your
$scope
.
Best Practices - 9) Testing
Thanks!
Questions?
Jasmine:

Jasmine is a behavior-driven development framework for testing JavaScript.
Mocha:

The fun, simple, flexible JavaScript test framework
QUnit:

A JavaScript Unit Testing framework, used by jQuery
A function which displays an error message.
A function which validates an email address.
A function which sorts a list of names.
A function which changes the state of a product to 'out of stock'.
A function which adds a list of numbers together.
Frameworks
Examples
Set up a mocked service to use in controller unit tests.
1 -
Minimize
/Avoid Watchers
2 - Avoid
ng-repeat
. If you have to use ng-repeat use infinite scrolling or pagination
3 - Use
Bind once
when possible (:: notation)
4 - Use
$watchCollection
instead of $watch (with a 3rd parameter)
5 - Use
ng-if
instead of
ng-show

6 - Use
console.time
to benchmark your functions
7 - Use
Batarang
to benchmark your watchers
8 - Use
Chrome Timeline and Profiler
to identify performance bottlenecks
Full transcript