17. javascript libraries - web front-end

43
JavaScript Libraries How To Create Our Own JS Library Ivan Zhekov Telerik Software Academy academy.telerik.com Front-end Developer http://joneff.info http://html5course.telerik.com

Upload: telerik-academy

Post on 14-Apr-2017

2.098 views

Category:

Technology


0 download

TRANSCRIPT

Page 1: 17. JavaScript libraries - Web Front-End

JavaScript LibrariesHow To Create Our Own JS Library

Ivan Zhekov

Telerik Software Academyacademy.telerik.com

Front-end Developerhttp://joneff.info

http://html5course.telerik.com

Page 2: 17. JavaScript libraries - Web Front-End

Table of Contents What is a JavaScript libraries Prominent JavaScript libraries

prototype js MooTools jQuery Dojo YUI KendoUI

2

Page 3: 17. JavaScript libraries - Web Front-End

Table of Contents (2) JavaScript Library Fundamentals

Object creation / inheriting Query Traversing Manipulation Insertion / Deletion Events AJAX Animations

3

Page 4: 17. JavaScript libraries - Web Front-End

Table of Contents (3) Recommended features

All spiced up for basic users Powerful syntax for advanced users Strong coding convention

4

Page 5: 17. JavaScript libraries - Web Front-End

What is a JSL?Have you seen a moose?

It’s nothing like it!

Page 6: 17. JavaScript libraries - Web Front-End

What is a JSL A JS library is pre-written code that aims to facilitate and /or jump start development, especially AJAX based tasks

A JS library: Works around browser differences Abstracts common work Adds sugar and spice

In addition it might have widgets, themes … and even more sugar

6

Page 7: 17. JavaScript libraries - Web Front-End

Library vs. Framework Technically speaking, it’s just text, so pick your favorite

Never the less mind that in order to call a library a framework, it needs: More features More cases Widgets Full stack of dev love

7

Page 8: 17. JavaScript libraries - Web Front-End

Prominent JSLA brief, based overview

Page 9: 17. JavaScript libraries - Web Front-End

Prototype Created 2005 by Sam Stephenson One of the corner stones of JS, IMO Features

Object creation, DOM query, traversal, manip, events, Ajax, utility methods…

Scriptacolous / Scripty for animations / fx

Sadly no development over the past year … my personal favorite

9

Page 10: 17. JavaScript libraries - Web Front-End

Prototype syntax Sample code// Get an element and attach eventvar header = $("header");header.observe("click", function() {

alert("Yay ... clicked :) ");});

// Delete all elements of tag name$$("a").each(Element.remove);

// Ajaxnew Ajax.Request(url, {

method: 'get',onSuccess: function(transport) {...}

});

10

Page 11: 17. JavaScript libraries - Web Front-End

MooTools Created 2005 by Vallerio Proietti Initially moo.fx was a FX lib for prototype

Developed over the years as a separate lib

Features inspired by Prototype, but different: Object creation, DOM query,

traversal, manip, events, Ajax, utility methods…

Some what active development 11

Page 12: 17. JavaScript libraries - Web Front-End

Mootools syntax Sample codevar header = $("header");header.addEvnet("click", function() {

alert("Yay ... clicked :) ");});

$$("a").each(function(element) {element.dispose();

});

var myRequest = new Request({url: url,onSuccess: function(responseText,

responseXML) {...}});myRequest.send();

12

Page 13: 17. JavaScript libraries - Web Front-End

jQuery Created 2006 by John Resig Initially just selectors Have become one of the most powerful and used js libraries in the web

Features DOM query, traversal, manip,

animations, Ajax, utility, plugins… Bundled with popular IDE’s Quite magical for n00bs 13

Page 14: 17. JavaScript libraries - Web Front-End

jQuery syntax Sample codevar header = $("#header");header.bind("click", function() {

alert("Yay ... clicked :) ");});

$("a").remove();

$.Ajax(url, {success: function(data) {...}

});

14

Page 15: 17. JavaScript libraries - Web Front-End

Dojo Created 2005 by John Resig Somewhat underestimated, but powerful library with many features

Features DOM query, traversal, manip,

animations, Ajax, utility, plugins… UI widgets Mobile

Just released 1.715

Page 16: 17. JavaScript libraries - Web Front-End

Dojo syntax Sample codevar header = dojo.byId("header");dojo.connect(header, "onclick", function() {

alert("Yay ... clicked :) ");});

dojo.query("a").orphan();

dojo.xhrGet({url: url,load: function(data) {...}

});

16

Page 17: 17. JavaScript libraries - Web Front-End

YUI Created 2005 by Yahoo! Home grown and developed Features

DOM query, traversal, manip, animations, Ajax, utility, plugins…

UI widgets Developer tools

Still actively developed

17

Page 18: 17. JavaScript libraries - Web Front-End

YUI syntax Sample code (for YUI3)YUI().use(["node", "io"], function (Y) {

var header = Y.one("#container");header.on("click", function() {

alert("Yay ... clicked :) ");});

Y.all("a").remove();

Y.io(uri)});

18

Page 19: 17. JavaScript libraries - Web Front-End

Kendo UI Just released by Telerik So far, build on top of jQuery, but improved: Blazing fast templates Excels performance and ease of use

Features: UI widgets, templates, data

visualizations Serves CSS as browser compiled

LESS Coming in mobile flavor soon

19

Page 20: 17. JavaScript libraries - Web Front-End

KendoUI syntax Sample code// Kendo doesn't do DOM it's all UI// It requires certain HTML to be on the page

// auto complete widget$("#autocomplete").kendoAutoComplete(["Item1", "Item2"]);

// calendar widget$("#calendar").kendoCalendar();

// dropdown widget$("#combobox").kendoComboBox([{text: "Item1", value: "1"}, {text: "Item2", value: "2"}]);

// fancy upload$("#files").kendoUpload(); 20

Page 21: 17. JavaScript libraries - Web Front-End

Other There are many, many, many, many, other js libraries out there Some deal with common tasks Other excel in UI There are those who do JS MVC And some do server side

Just ask G about them

21

Page 22: 17. JavaScript libraries - Web Front-End

Building our own JSLReady! Set! Go!

Page 23: 17. JavaScript libraries - Web Front-End

Roadmap We begin at the very end (feature wise)

Ensure code quality Homogenous syntax Module patterns Get the job done, add candy later Let’s pretend that there are NO old browsers

Then suddenly remember it and add support 23

Page 24: 17. JavaScript libraries - Web Front-End

Recommended featuresUnicorns and rainbows

Page 25: 17. JavaScript libraries - Web Front-End

Code Convention What is a coding convention?

A set of writing rules concerning some or all aspects of the coding

How to comment How to name functions, variables,

params etc. White spaces…

25

Page 26: 17. JavaScript libraries - Web Front-End

Code Convention (2) Why have one?

Homogenous code Easier to read May help avoid problems in the

future Some habits are just good

26

Page 27: 17. JavaScript libraries - Web Front-End

Powerful Syntax That would be the normal way Libraries are generally wrapping native functionality All native functionality should be

achievable trough parameter combinations

One of two ways to do that: Have a single method for many

operations Have a method for each operation

27

Page 28: 17. JavaScript libraries - Web Front-End

Syntax sugar Not a new thing – almost 50 years old concept

Syntax sugar means having shorthand methods that do heavy lifting

Sort of a Swiss army knife for some stuff

Benefits: Easier to read / compact code Gentle learning curve More expressive

Cons: random hate… above all

28

Page 29: 17. JavaScript libraries - Web Front-End

Documentation Documentation is essential

Don’t over document Don’t under document

Document just right: No more or less than needed Concrete sentences, clear language Avoid disambiguation Try to be neutral

Update the docs in a timely manner! 29

Page 30: 17. JavaScript libraries - Web Front-End

Examples The best documentation has examples Never the less have separate

examples Organize examples in scenarios Describe scenarios fluently Elaborate if a scenario is a bad

practice Help users choose between scenarios Provide at least one example per

scenario Have as many examples as possible Try not to mix code with content

30

Page 31: 17. JavaScript libraries - Web Front-End

Community Don’t underestimate the community The community is using the library They are important, but not too

important Have your own opinion, but listen to

others A proper community needs

Commenting articles, forums, tracking system, contribution system

Even awards A community is created by itself

And is dissolved that way

31

Page 32: 17. JavaScript libraries - Web Front-End

Let’s startChat: show me the code

Page 33: 17. JavaScript libraries - Web Front-End

Code convention It’s a bit see as we go, but just a start: //comments preferably Code indentation is one tab (set to

four spaces) Functions and properties are in

camelCase Objects and constructors are in

PascalCase If we need a getter use

get_property If we need private use _property No curly braces for single line

control structures Use white space accordingly

33

Page 34: 17. JavaScript libraries - Web Front-End

Object creation Object creation is important for:

Custom utility objects UI widgets

Magical base is overrated (IMO) Actually, magic is overrated

Simple inheriting first, multiple later

Object factory Prototype.create(…)

34

Page 35: 17. JavaScript libraries - Web Front-End

Querying the DOM Specificity first

A method for one A method for all / sub querying

Return what’s expected: One, Many or NULL

Use built in methods where possible

Optimize by analyzing parameters

35

Page 36: 17. JavaScript libraries - Web Front-End

DOM traversal Not that different from querying

node.nodeType == 1 means HTML element

The parentNode is usually an element

Utility methods for: Siblings – all, left, right, single Children – first, last, all Recursive parents

Selectors based traversing 36

Page 37: 17. JavaScript libraries - Web Front-End

Manipulation Attributes are mostly the same in HTML and DOM With few minor exceptions

First use concrete attributes Then normalize input for easier

development Mind that the style attribute is a bit different

We could make it work to set or get multiple attributes at once

Regardless of the choice for implementation, setting and getting props must work the same

37

Page 38: 17. JavaScript libraries - Web Front-End

DOM insertions / deletions

Cover the basic DOM insertion Add extension methods for easier

insertions, like prepend, insertAfter etc.

Remember that innerHTML works faster in some cases and documentFragment in the rest

Do we eval scripts upon insertion?

38

Page 39: 17. JavaScript libraries - Web Front-End

DOM events For a proper event system

Events should not bubble e.g. last param is false

We can make syntax that omits it Unless one wants to specify it

explicitly What do we do about anonymous events?

How do we mass remove events? Event delegates Events handlers for collection of elements

39

Page 40: 17. JavaScript libraries - Web Front-End

Ajax Just the basics

Implement methods for: post, get, put, delete

Use native objects Don’t wait for forever to timeout Status code vs. words based

callbacks Should the Ajax invoker be void?

Plain old fetching data to populate elements

Persistent connections40

Page 41: 17. JavaScript libraries - Web Front-End

Animations Ways to do it:

Interval with fixed steps Interval with time based steps Native request animation frame

Stopping animations and reverting to base

Chaining animations Animation callbacks Anything else you can think of

41

Page 42: 17. JavaScript libraries - Web Front-End

форум програмиране, форум уеб дизайнкурсове и уроци по програмиране, уеб дизайн – безплатно

програмиране за деца – безплатни курсове и уроцибезплатен SEO курс - оптимизация за търсачки

уроци по уеб дизайн, HTML, CSS, JavaScript, Photoshop

уроци по програмиране и уеб дизайн за ученициASP.NET MVC курс – HTML, SQL, C#, .NET, ASP.NET MVC

безплатен курс "Разработка на софтуер в cloud среда"

BG Coder - онлайн състезателна система - online judge

курсове и уроци по програмиране, книги – безплатно от Наков

безплатен курс "Качествен програмен код"

алго академия – състезателно програмиране, състезанияASP.NET курс - уеб програмиране, бази данни, C#, .NET, ASP.NET

курсове и уроци по програмиране – Телерик академия

курс мобилни приложения с iPhone, Android, WP7, PhoneGapfree C# book, безплатна книга C#, книга Java, книга C# Дончо Минков - сайт за програмиране

Николай Костов - блог за програмиранеC# курс, програмиране, безплатно

?? ? ?

??? ?

?

? ?

??

?

?

? ?

Questions?

?

JavaScript Libraries

http://academy.telerik.com

Page 43: 17. JavaScript libraries - Web Front-End

Free Trainings @ Telerik Academy

"Web Design with HTML 5, CSS 3 and JavaScript" course @ Telerik Academy html5course.telerik.com

Telerik Software Academy academy.telerik.com

Telerik Academy @ Facebook facebook.com/TelerikAcademy

Telerik Software Academy Forums forums.academy.telerik.com