58
$("#presentation") .attr("title", "JavaScript DSLs " + "for the Client Side") By Dionysios G. Synodinos

$("#presentation") . attr ("title", " JavaScript DSLs " + " for the Client Side ")

  • Upload
    gaenor

  • View
    35

  • Download
    0

Embed Size (px)

DESCRIPTION

$("#presentation") . attr ("title", " JavaScript DSLs " + " for the Client Side "). By Dionysios G. Synodinos. Overview. What is a DSL?. - PowerPoint PPT Presentation

Citation preview

Page 1: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

$("#presentation").attr("title",

"JavaScript DSLs " +"for the Client Side")

By Dionysios G. Synodinos

Page 2: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Overview

DSL Foundati

on

JavaScript: The

Language

Client-Side

Frameworks

The Challeng

e for HTML 5

Create your own

JavaScript DSL

Page 3: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

What is a DSL?

A domain-specific language (DSL) is a programming language or executable specification language that offers, through appropriate notations and abstractions, expressive power focused on, and usually restricted to, a particular problem domain.

Page 4: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Characteristics

Focused expressive power. Usually small, offering only a

restricted suite of notations and abstractions.

Not necessarily Turing complete. May contain an entire general-

purpose language (GPL) as a sublanguage

Usually declarative

Page 5: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Advantages Domain experts themselves can understand,

validate, modify, and even develop DSL programs

DSL programs are concise, self-documenting to a large extent, and can be reused for different purposes

DSLs embody domain knowledge, and thus enable the conservation and reuse of this knowledge

DSLs allow validation and optimization at the domain level

Page 6: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Disadvantages

Costs of designing & implementing Cost of maintenance Costs of education for users Difficulty of balancing between

domain-specificity and general-purpose programming language constructs.

Potential loss of efficiency when compared with hand-coded software.

Page 7: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Two types of DSLs

Internal•Change the feel of the host language to be better suited for a domain

External•External DSLs have their own custom syntax and you write a full parser to process them.

Page 8: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Well-known DSLs

Make, Ant, NAnt, Rake

•Software Builds

SQL•Relational Data Manipulation

HQL, JPQL

•OO Data Querying

XSL•XML Transformations

CSS •Styling documents written in MLs

Regular Expressions

•String Identification

JavaFX Script

•Rich Internet Applications

Page 9: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Nature of JavaScript

“Simple”, highly dynamic, object-based language

Mixture of object-based and functional programming

Takes its major ideas from the languages Self and Scheme.

Page 10: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Scheme

One of the two main dialects of Lisp (the other being Common Lisp) and best known for its support of functional programming.

Its philosophy is very minimalist Provides as few primitive notions as

possible Lets everything else be provided by

programming libraries

Page 11: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Lisp

Lisp programs can manipulate source code as a data structure, giving rise to the macro systems that allow programmers to create new syntax or even new domain-specific programming languages embedded in Lisp.

Page 12: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

JavaScript Goodness

C-like syntax OO syntax mimics Java Prototype based Inheritance Dominant in HTML scripting AJAX, Adobe AIR, Google Gears Mozilla Rhino XML via DOM JSON Only mainstream language with real specs Java and .NET support

Page 13: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

People usually complain about… Lack of namespaces method_missing() Prototype Weirdness

Page 14: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

… but is JavaScript any good for DSL?

Page 15: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Method Chaining

Make modifier methods return the host object so that multiple modifiers can be invoked in a single expression.

YES

Page 16: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Nested Function

Compose functions by nesting function calls as arguments of other calls.

YES

Page 17: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Convenient Literal Collection Expression

Have lists and maps, with a concise literal syntax built-in in order to express language constructs. Lists are good for multiple items of the same thing while Maps work well for an unordered argument list

YES

Page 18: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Closures

Are fragments of code that can be easily declared in expressions and passed around as objects. For DSL purposes they are very good at providing a limited context for a section of the code.

YES

Page 19: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Macros

TextualSyntactic

NO

Page 20: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

…coping with the lack of macros outside of the language

Use a text editor snippet (e.g. Eclipse Templates)

Use a x-to-JavaScript compiler like GWT

Page 21: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Mimicking Macros #1if (!(conditional)) { statements}

unless (conditional) { statements}

// use functional literalvar unless = function(conditional, statements) { if (!(conditional)) { return statements(); }}// now call itunless(conditional, function() { statements;});

Page 22: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Mimicking Macros #2if (!(conditional)) { statements}

unless (conditional) { statements}

var unless = function(conditional, statements) {return 'if (!('+conditional+')) {'+ statements + '}';}

// use eval()eval(unless("conditional", "statements"))

Page 23: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Annotations

An Annotation allows a programmer to attach attributes to programming constructs such as classes and methods. These annotations can be read during compilation or at runtime.

YES

Page 24: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

…so what can you do will all this goodness?

Page 25: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Example: Project JS.Class

A library designed to facilitate OO development in JavaScript. It implements Ruby’s core object, module and class system and some of its metaprogramming facilities, giving you a powerful base to build well-structured OO programs.

Page 26: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

JS.Class Supports Classes and modules with Ruby-compatible

inheritance Subclassing and mixins Late-binding arguments-optional super calls

to parent classes and mixins Singleton methods included, extended and inherited hooks Method binding Ports of various standard Ruby modules,

including Enumerable, Observable, Comparable, Forwardable

Page 27: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

JS.Class Example #1: Classes

// Define the classvar Animal = new JS.Class({ initialize: function(name) { this.name = name; },

speak: function(things) { return 'My name is ' + this.name + ' and I like ' + things; }});

// Create the objectvar nemo = new Animal(‘Lassie');

// Call class methodnemo.speak('swimming')// -> "My name is Lassie and I like swimming"

Page 28: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

JS.Class Example #2: Method Chaining that feels like Macros

//Create a MethodChain object called chainvar chain = new JS.MethodChain();

// Call map(), join() and replace() on it chain

.map(function(s) { return s.toUpperCase() }) .join(', ')

.replace(/[aeiou]/ig, '_');

// Now chain object calls the stored chain on any object you pass to its fire() method

chain.fire(['foo', 'bar']) // -> "F__, B_R"

A mechanism for storing a sequence of method calls and then executing that sequence on any object you like.

Page 29: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

A general word of advice

"is" was proposed to be a reserved word in ecmascript 4, so using it in a DSL might be an issue.

Page 30: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Frameworks, frameworks, frameworks…

Page 31: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Dojo Toolkit Dojo is more verbose than other frameworks Heavily uses namespaces! Dion Almear wanted to

make a plugin for his editor to grey-out the string “dojo.” :)

prefers dojo.byId and dojo.query over the popular $ operator

Although Dojo was inspired by Python, AOP, PHP, Java, and a variety of functional programming language constructs like hitch, mixins, delegation, and more.

However, the Dojo team explicitly avoid using any patterns from other languages, and made great efforts to leverage the patterns unique to JavaScript.

Page 32: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Dojo and DSL?

“Dojo takes advantage of the flexibility of JavaScript rather than trying to provide a domain specific language on top of JavaScript.”

Dylan SchiemannCEO of SitePen & co-creator of the Dojo Toolkit.

http://www.sitepen.com/blog/2008/10/27/debunking-dojo-toolkit-myths/

Page 33: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Does this mean no DSL with Dojo?

JavaScript is an open language and you can poke around

Page 34: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

$() for Dojo

$ = dojo.mixin(function(){ return dojo.mixin(dojo.query.apply(this, arguments), $.fn); },dojo,{ fn: {} }

);

Page 35: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Plugd for Dojo

plugd is a collection of useful functionality built on and around Base

$("p.baz") .appendTo("body") .addClass("bar") .onclick(function(e){ e.target.innerHTML = “Hello World"; });

“The API's found in plugd are loosely based on my favorite bits of jQuery”Pete Higgins

Page 36: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

jQuery Library

Very easy and powerful for DOM manipulation

Heavily uses $() Uses CSS selectors

$(selector)▪ Returns an array of elements that match the

selector, ▪ e.g. $(p a)

Feels like a CSS extension mechanism

Page 37: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

jQuery Library cont.

$() wraps elements with additional functionality and adds several useful oparations e.g. $("div.areaToBeRemoved").fadeOut();

Since methods return grous of elements, you can have method chaining e.g. $("p").addClass("test").show().html("foo");

Page 38: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

jQuery Implements CSS Selectors$("p > a")

$(“p:first-child")

$("tr:nth-child(1)")

Page 39: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

jQuery has basic support for XPath

$("iframe[id^='frame']")

$("a[href$=pdf]")

$("//div ~ form")

Page 40: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

jQuery custom selectors

$("p:even")

$("div:hidden").show();

$("p:first").css("fontWeight","bold");

Page 41: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

jQuery for AJAXvar xhr;

if (window.XMLHttpRequest) { xhr = new XMLHttpRequest();}else if (window.ActiveXObject) { xhr = new

ActiveXObject("Msxml2.XMLHTTP");}else { throw new Error("Ajax not supported");}

xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status >= 200 && xhr.status <

300) {

document.getElementById('myContainer') .innerHTML = xhr.responseText; } }}

xhr.open('GET','/imported.html');xhr.send();

$('#myContainer').load('imported.html');

$("#myContainer").load("imported.html")

Page 42: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Project: Event.Behavior

A Prototype extension that tries to add "natural language event programming for Prototype".

Example:

with(Event.Behavior){ set_style(styles).on(paragraphs).when(selects).change();

}

Page 43: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Event.Behavior: Basic Sentence ConstructionThe basic rule is: one verb construct, followed by when(), followed by at least one event or condition. If no events are specified, changes() is implicit.

Page 44: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Event.Behavior cont.with(Event.Behavior){

add_class_name('black').to('paragraph')

.when('color_select').is('black')

add_class_name('bold')

.to('paragraph').when('weight_select')

.is('bold')

show('province_field').when(‘country')

.is(‘Canada') }

Page 45: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Project: Ojay

Provides a DSL-style API for writing specs for validating form input, handling errors when they occur, and allowing forms to be submitted using Ajax.

Is an interface that wraps the Yahoo! User Interface library in order to make code easier to read and write, by allowing more sentence-like OO syntax and minimizing repetition.

Page 46: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Ojay Example

$('a#run-this-code').on('click', $.stopEvent).setContent('Running...')._('#example').animate({

height: {to: 0}, opacity: {from: 1, to: 0} }, 0.5)._($.HTTP).GET('/service/hello.html').insertInto('#example')._('#example').animate({

height: {to: 80}, opacity: {from: 0, to: 1} }, 0.7);

Page 47: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Ojay supported CSS Selectors document.querySelectorAll YAHOO.util.Selector Ext.DomQuery Sizzle Peppy

Pluggable CSS Selector Engine used in jQuery

Page 48: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Project: TrimQueryProvides component that lets you have the power of SQL queries while running in a web browser.

The engine supports several SQL concepts like:

INSERT, UPDATE, DELETESELECT ... FROMWHERE clausesLIKE supportORDER BY (sorting on multiple columns, ASC and DESC)AS (aliases)GROUP BY, HAVING aggregationSUM, COUNT, AVG aggregate functionsself joinsLIMIT and offsets

… in the browser with standard JavaScript!

Page 49: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

TrimQuery Example: Define Schemavar columnDefs = {Invoice : { id : { type: "String" },

total : { type: "Number" },

custId : { type: "String" } },

Customer : { id : { type: "String" },acctBalance : { type: "Number" }

}};

Page 50: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

TrimQuery Example cont.: Create data recordsvar tableData = {

Invoice : [ { id: 1, total: 100, custId: 10 },

{ id: 2, total: 200, custId: 10 },

{ id: 3, total: 300, custId: 10 },

{ id: 4, total: 400, custId: 20 } ],

Customer : [ { id: 10, acctBalance: 1000 }, { id: 20, acctBalance: 2000 }, { id: 30, acctBalance: 3000 } ] };

Page 51: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

TrimQuery Example cont.: Execute a query// Import schemavar queryLang = TrimPath.makeQueryLang(columnDefs);

// Do a SELECT statement.var statement = queryLang.parseSQL(

"SELECT Customer.id, Customer.acctBalance, Invoice.total " +"FROM Customer, Invoice " +"WHERE Customer.id = Invoice.custId " +"ORDER BY Customer.id ASC");

// Execute queryvar results = statement.filter(tableData);

// ->[ { id: 10, acctBalance: 1000, total: 100 },// { id: 10, acctBalance: 1000, total: 200 },// { id: 10, acctBalance: 1000, total: 300 },// { id: 20, acctBalance: 2000, total: 400 } ]

Page 52: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

New functionality in HTML 5Several new APIs are exposed to JavaScript developers and framework creators including:

Canvas for 2D Drawing

Built-in Media

Support

Offline Storage

Web Sockets

Page 53: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Built-in Media Support<video src=“somevideo.ogg“ id=“myvideo“></video><script> var video = document.getElementById(“myvideo");</script><p><button type="button" onclick="video.play();">Play</button> <button type="button" onclick="video.pause();">Pause</button> <button type="button" onclick="video.currentTime = 0;">&lt;&lt; Rewind</button>

show_video(“somevideo.ogg").add_controls([’play’, ’pause’, ’rewind’]);

DSL for Media

Page 54: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

2D Drawing with <canvas>if (canvas.getContext){

// use getContext to use the canvas for drawing var ctx = canvas.getContext('2d');

// Draw shapes ctx.fillRect(25,25,100,100); ctx.clearRect(45,45,60,60); ctx.strokeRect(50,50,50,50); }

var exampleData = [

{ time: 10, count: 7382 },{ time: 20, count: 1852 },{ time: 35, count: 2397 },{ time: 50, count: 1442 },{ time: 55, count: 1854 }

]

plot().chart_type('CurvedArea').with_data(exampleData)

Charting DSL

Page 55: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Web Socketsvar con = new WebSocket("ws://mywebsocket.com");con.onopen = function(evt) { alert("Connection open ..."); };con.onmessage = function(evt) { alert( "Received Message: " + evt.data); };con.onclose = function(evt) { alert("Connection closed."); };con.postMessage("Hello Web Socket! ");con.disconnect();

connect_to("ws://websocket.stockquotes.com").get_quotes("MSFT")

.when().falls_under("18$")

.action(['alert','Stock is dropping!'])

Stock Quotes

DSL

Page 56: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Offline Storagedb = openDatabase("dbTest", "1.0", "First Database", 300000);db.transaction(function(tx) {

tx.executeSql("SELECT * FROM MyTb”, [], function(tx, result) { alert(result.rows.item(0)['id']);

}); });

var acustomer = ['John', 'Doe', '[email protected]'];db.store(acustomer);

ORM DSL

Page 57: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

Create your own JavaScript DSL Create the specs in natural language

Show us-state field when country select box is “US” Find DSL notation that is closest to the

problem domaincreate_dynamic_field("show", "us-state-field", "country", "USA")show("show-state-field").when("country").is("USA")

Start building the functions that get chained in an iterative and incremental manner

Having proper tests helps big time!

Page 58: $("#presentation") . attr ("title", " JavaScript DSLs  " + " for the Client Side ")

References Macros in JavaScript please

http://peter.michaux.ca/articles/macros-in-javascript-please Declarative JavaScript programming

http://www.dotnetjunkies.com/WebLog/anoras/archive/2004/08/09/21502.aspx

Project JS.Class http://jsclass.jcoglan.com/ Dojo Tookit http://dojotoolkit.com/ Creating Your Own $ [in Dojo]

http://dojocampus.org/content/2008/03/13/creating-your-own/

jQuery Library http://jquery.com/ Even. Behavior http://livepipe.net/extra/event_behavior Ojay http://code.google.com/p/ojay/ TrimQuery http://code.google.com/p/trimpath/wiki/TrimQuery Metaprogramming JavaScript

http://www.adamlogic.com/wp-content/uploads/2007/03/metaprogramming-javascript.pdf