Vous êtes sur la page 1sur 35

2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps

https://www.dartlang.org/docs/synonyms/ 1/35
Getting started
Code embedding
// Use both script tags to reach all browsers
// For browsers with the Dart VM
<script type='application/dart' src='program.dart'></script>
// The following will kickstart the Dart engine and
// try to automatically load the javascript version
// of your app for non-Dartium browsers.
<script src="packages/browser/dart.js">
</script>
<script src='program.js'></script>
Entry point
// REQUIRED.
main() {
// this is the entry point to the program
}
// Or
main(List<String> args) {
// ...
}
// Not required.
function main() {
// To be used as the entry point, but it must be
// called manually.
}
main();
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 2/35
// Sometimes the entry point is written as an
// anonymous function
(function(){
// Code to be run automatically on execution
})();
Detect language unavailability
<script type='text/javascript'>
if (navigator.userAgent.indexOf('(Dart)') === -1) {
// Browser doesn't support Dart
}
</script>
<noscript>
Your browser doesnt support JavaScript.
</noscript>
Printing to the console
print('Level completed.');
console.log('Level completed.');
Modal alerts
import 'dart:html';
window.alert('Clicked on the button.');
alert('Clicked on the button.');
Code modularity (Learn more )
Define a library
// declares the following is in the animals library
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 3/35
library animals;
class Dog {
noise() => 'BARK!';
}
// No native implementation.
// Consider require.js and AMD
Use a library
import 'animals.dart';
var fido = new Dog();
// prefixes are supported to avoid namespace collisions
import 'animals.dart' as pets;
var fido = new pets.Dog();
// no native implementation
// consider require.js and AMD
Variables (Learn more )
Create + assign value
// Dart variables can be typed...
String myName = 'Aaron';
// but they don't need to be
var myOtherName = 'Aaron';
var myName = 'Aaron';
Default value
var myName;
// == null
int x;
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 4/35
// == null
var myName;
// == undefined
Hoisting
// Dart does not hoist variables. The following
// method will issue a compilation error of "cannot resolve name"
printName() {
print('Hello, $name'); // compilation error here
var name = 'Bob';
}
// JavaScript "hoists" variables to the top of
// their scope. So the following function:
function printName() {
console.log('Hello, ' + name);
var name = 'Bob';
}
// is equivalent to this function:
function printName() {
var name;
console.log('Hello, ' + name);
name = 'Bob';
}
printName();
// Hello, undefined
Final variables
final name = 'Bob';
// you can combine types and final
final String name = 'Bob';
// Trying to reassign a final variable raises an error
name = 'Alice';
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 5/35
// ERROR: cannot assign value to final variable
// no support
Collections (Learn more )
Arrays / Lists
var a = new List();
var a = [];
var a = ['apple', 'banana', 'cherry'];
a.add('orange');
a.length == 4;
// In Dart you can use generics.
var a = new List<String>();
var a = new Array();
var a = [];
var a = ['apple', 'banana', 'cherry'];
a.push('orange');
a.length == 4;
Custom sort
var numbers = [42, 2.1, 5, 0.1, 391];
numbers.sort((a, b) => a - b);
// == [0.1, 2.1, 5, 42, 391];
var numbers = [42, 2.1, 5, 0.1, 391];
numbers.sort(function(a, b) {
return a - b;
});
// == [0.1, 2.1, 5, 42, 391]
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 6/35
Key-value pairs
// Dart has a Map interface for key-value pairs
var periodic = {};
var periodic = new Map();
// An empty key-value pair can be declared
// in two different ways in JavaScript
var periodic = new Object();
var periodic = {};
Appropriate keys
// Map literals must use strings as keys
var periodic = {
'gold' : 'AU',
'silver' : 'AG'
};
// Map constructors can use any object as a key
var favoriteIceCream = new Map();
favoriteIceCream[new Kid('Billy')] = 'vanilla';
var periodic = {
gold: 'AU',
silver: 'AG'
};
var periodic = {
'gold': 'AU',
'silver': 'AG'
};
Accessing values
// Values can only be 'get' or 'set' by using the square
// bracket notation. Dot notation does not work
periodic['gold'] // == 'AU'
periodic['gold'] = 'Glitter';
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 7/35
// You can set a key if it does not exist first.
// Runs a function to generate the value.
periodic.putIfAbsent('Xenon', () => 'XE');
periodic.gold // == 'AU'
periodic['gold'] // == 'AU'
periodic.gold = 'Glitter';
periodic['gold'] = 'Glitter';
Sets (collections of unique items )
var fruits = new Set();
fruits.add('oranges');
fruits.add('apples');
fruits.length // == 2
fruits.add('oranges'); // duplicate of existing item
fruits.length // == 2
// no native JavaScript equivalent
Queues (FIFO )
// Queues are optimized for removing items from the head
var queue = new Queue();
queue.add('event:32342');
queue.add('event:49309');
print(queue.length); // 2
var eventId = queue.removeFirst();
print(eventId == 'event:32342'); // true
print(queue.length); // 1
// No dedicated queue, use an array.
var queue = [];
queue.push('event:32342');
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 8/35
queue.push('event:49309');
console.log(queue.length); // 2
var eventId = queue.shift();
console.log(eventId === 'event:32342');
console.log(queue.length); // 1
Strings (Learn more )
Raw strings
var rawString = r'The following is not expanded to a tab \t';
var escapedString = 'The following is not expanded to a tab \\t';
rawString == escapedString // == true
// JavaScript does not have 'raw' strings.
// All escaping must be done manually.
var escapedString = 'A tab looks like \\t';
Interpolation
var name = 'Aaron';
var greeting = 'My name is $name.';
var greetingPolish = 'My Polish name would be ${name}ski.';
// calculations can be performed in string interpolation
element.style.top = '${top + 20}px';
var name = 'Aaron';
var greeting = 'My name is ' + name;
var greetingPolish = 'My Polish name would be ' + name + 'ski';
element.style.top = (top + 20) + 'px';
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 9/35
Concatenation
// Adjacent string literals concatenate.
var longMessage = 'This is a very long line. '
'It is concatenated into one string.';
// Using + also works.
var anotherMessage = 'This is also a very long line. ' +
'It is concatenated with a +.';

// Or use string interpolation.
var name = 'Aaron';
var greeting = 'My name is $name.';
var longMessage = 'This is a very long line. ' +
'It is concatenated into one string.';

var name = 'Aaron';
var greeting = 'My name is ' + name;
Substring
'doghouses'.substring(3, 8); // == 'house'
'doghouses'.substring(3, 8) // == 'house'
'doghouses'.substr(3, 5) // == 'house'
Replace all occurences
'doghouses'.replaceAll('s','z'); // == 'doghouzez'
'doghouses'.replace(/s/g, 'z') // == 'doghouzez'
Replace one occurence
'racecar'.replaceFirst('r', 'sp'); // == 'spacecar'
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 10/35
'racecar'.replace(/r/, 'sp') // == 'spacecar'
Multi-line strings
// Dart ignores the first new-line (if it is directly after
// the quotes), but not the last.
var string = '''
This is a string that spans
many lines.
''';
var string =
'This is a string that spans\n' +
'many lines.\n';
Split into an array
var animals = 'dogs, cats, gophers, zebras';
var individualAnimals = animals.split(', ');
// == ['dogs', 'cats', 'gophers', 'zebras'];
var animals = 'dogs, cats, gophers, zebras';
var individualAnimals = animals.split(', ');
// == ['dogs', 'cats', 'gophers', 'zebras'];
Test whether a string starts with a substring
// Dart string objects have a built-in startsWith method
'racecar'.startsWith('race'); // == true
'racecar'.startsWith('pace'); // == false
// JavaScript has no built-in startsWith function
String.prototype.startsWith = function(beginning) {
var head = this.substr(0, beginning.length);
return head == beginning;
}
'racecar'.startsWith('race') // == true
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 11/35
'racecar'.startsWith('pace') // == false
Booleans (Learn more )
If statements
var bugNumbers = [3234,4542,944,124];
if (bugNumbers.length > 0) {
print('Not ready for release');
}
var bugNumbers = [3234,4542,944,124];
if (bugNumbers.length > 0) {
console.log('Not ready for release');
}
Ternary statements
var bugNumbers = [3234,4542,944,124];
var status = bugNumbers.length > 0 ? 'RED' : 'GREEN';
print('The build is $status');
var bugNumbers = [3234,4542,944,124];
var status = bugNumbers.length > 0 ? 'RED' : 'GREEN';
console.log('The build is ' + status);
Checking for empty string
var emptyString = '';
if (emptyString.isEmpty) {
print('use isEmpty');
}
var emptyString = '';
if (!emptyString) {
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 12/35
console.log('empty strings are treated as false');
}
Checking for zero
var zero = 0;
if (zero == 0) {
print('use == 0 to check zero');
}
var zero = 0;
if (!zero) {
console.log('0 is treated as false');
}
Checking for null
var myNull = null;
if (myNull == null) {
print('use == null to check null');
}
var myNull = null;
if (!myNull) {
console.log('null is treated as false');
}
Checking for NaN
var myNaN = 0/0;
if (myNaN.isNaN) {
print('use isNaN to check if a number is NaN');
}
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 13/35
var myNaN = NaN;
if (!myNaN) {
console.log('NaN is treated as false');
}
Checking for undefined
// Dart does not have a concept of undefined
if (typeof isUndefined === 'undefined') {
console.log('undefined');
}
Value and identity equality
/*
* In Dart, == will check the following, in order:
* 1) if either x or y is null, then return identical(x, y)
* 2) otherwise, return x.==(y)
*/
/*
* This means:
* a) use identical(a, b) instead of === (there is no ===)
* b) when implementing ==() you don't have to worry about
* manually checking for null arg
* c) you can't define your own type that considers itself
* equal to null
* d) null == null
*/
// therefore, the following code will work:
var letterA = 'A';
var charA = new String.fromCharCodes([65]);
// String defines equality as 'same character codes in same order'
letterA == charA // == true
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 14/35
// However, the following is different than JavaScript
var number5 = 5;
var char5 = '5';
number5 != char5 // == true, because of different types
// You can implement == in your own class
class Person {
String name;
String ssn;
Person(this.name, this.ssn);

bool operator ==(Person other) {
return ssn == other.ssn;
}
}
new Person('Bob', '111') == new Person('Robert', '111');
var letterA = 'A';
var charA = String.fromCharCode(65);
// JavaScript converts both values to the same type
// before checking their value with 'double equals'.
letterA == charA // == true
// Similarly...
var number5 = 5;
var char5 = '5';
// This comparison triggers type conversion
number5 == char5 // == true
// 'triple equals' checks type and value
letterA === charA // == true
number5 === char5 // == false
Functions (Learn more )
Function definition
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 15/35
// Specifying the return type of the function
// in Dart is optional.
fn() {

return true;
}
// can also be written as
bool fn() {

return true;
}
function fn() {

return true;
}
Return value
// Like JavaScript, use the 'return' keyword in a function
// definition to return a value.
fn() {
return 'Hello';
}
fn(); // == 'Hello'
// A function with no return value returns null.
doNothing() {
// nothing
}
doNothing(); // == returns null
// if the body of the function is returning a single expression,
// this is the short form
fn() => true;
function fn() { return 'Hello'; }
fn(); // == 'Hello'
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 16/35
(function(){})() // == returns undefined
Assign a function to a variable
var loudify = (msg) => msg.toUpperCase();
loudify('not gonna take it anymore'); // NOT GONNA TAKE IT ANYMORE
var loudify = function(msg) {
return msg.toUpperCase();
}
loudify('not gonna take it anymore');
// NOT GONNA TAKE IT ANYMORE
Optional parameters
fn(a, b, c) => c;
fn(1); // ERROR: NoSuchMethodException
fn(1, 2, 3); // == 3
// Dart specifies optional parameters with square braces
fn(a, [b, c]) => c;
fn('a'); // == null
function fn(a, b, c) { return c; };
fn(1) // == undefined
fn(1, 2, 3) // == 3
Parameters with default values
String send(msg, [rate='First Class']) {
return '${msg} was sent via ${rate}';
}
send('hello'); // == 'hello was sent via First Class'
send("I'm cheap", '4th class'); // == "I'm cheap was sent via 4th class"
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 17/35
function send(msg, rate) {
rate = rate || 'First Class';
return msg + " was sent via " + rate;
}
send('hello') // == 'hello was sent via First Class'
send("I'm cheap", '4th class') // == "I'm cheap was sent via 4th class
Named parameters
String send(msg, {rate: 'First Class'}) {
return '${msg} was sent via ${rate}';
}
// you can use named parameters if the argument is optional
send("I'm cheap", rate:'4th class'); // == "I'm cheap was sent via 4th class"
// JavaScript does not have native support for named parameters
Variable number of arguments
// Dart does not support variable numbers of arguments
function superHeros() {
for (var i = 0; i < arguments.length; i++) {
console.log("There's no stopping " + arguments[i]);
}
}
superHeros('UberMan', 'Exceptional Woman', 'The Hunk');
Iterators (Learn more )
For loops for lists
var colors = ['red', 'orange', 'green'];
for (var i = 0; i < colors.length; i++) {
print(colors[i]);
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 18/35
}
var colors = ['red', 'orange', 'green'];
for (var i = 0; i < colors.length; i++) {
console.log(colors[i]);
}
For-in loops
var fruits = ['orange', 'apple', 'banana'];
// 'in' notation in Dart returns the element
// of the list, not the index
for (var fruit in fruits) {
print(fruit);
}
var fruits = ['orange', 'apple', 'banana'];
// 'in' notation in JavaScript iterates through
// the properties, not values, of an object.
// Thus it returns the indices of the array
// and any items add to the Array prototype.
for (var i in fruits) {
console.log(fruits[i]);
}
For loops for objects/maps
var data = { };
for (var key in data.keys) {
print('$key, ${data[key]}');
}
// Alternatively, the forEach loop is a method on a Map in Dart.
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 19/35
data.forEach((key, value) {
print('${key}, ${value}');
});
var data = { };
for (var key in data) {
console.log('key', key);
console.log('value', data[key]);
}
Closures and counters in loops
// Dart doesn't reuse and close over the same
// loop variable in each iteration
var callbacks = [];
for (var i = 0; i < 2; i++) {
callbacks.add(() => print(i));
}
callbacks[0]() // == 0
var callbacks = [];
// A closure must be used to preserve the return for
// each function at each step of the loop. Otherwise
// every entry in callbacks will return 2;
for (var i = 0; i < 2; i++) {
(function(_i) {
callbacks.push(function() {
return _i;
});
})(i);
}
// Without the internal closure, the result is 2
callbacks[0]() // == 0
// ECMAScript 6 can support this with the use of blocks
let callbacks = [];
for (let i = 0; i < 10; i++) {
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 20/35
let j = i;
callbacks.push(function() { print(j) });
}
Classes (Learn more )
Define
class Person {
String name;
String greet() => 'Hello, $name';
}
function Person() {
this.name = null;
};
Person.prototype.greet = function() {
return 'Hello, ' + this.name;
}
Constructor with parameter
class Person {
String name;
Person(String name) {
this.name = name;
}
}
// Shorter alternative
class Person {
String name;
// parameters prefixed by 'this.' will assign to
// instance variables automatically
Person(this.name);
}
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 21/35
function Person(name) {
this.name = name;
};
Instantiate
var person = new Person();
var person = new Person();
Reflection
var name = "Bob";
name.runtimeType // == String
var name = 'Bob';
typeof name // == 'String'
Check the type
var name = 'Bob';
name is String // == true
name is! int // == true
var name = 'Bob';
// Because of javascript's type system we
// need to check both instanceof and typeof
name instanceof String || typeof name === 'string';
// == true
(!(name instanceof Number || typeof name === 'number'));
// == true
Subclass
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 22/35
class Person {
String name;
Person(this.name);
String greet() => 'Hello, $name';
}
class Employee extends Person {
num salary;
Employee(String name, this.salary) : super(name);

void grantRaise(num percent) {
percent /= 100;
salary += (salary * percent).toInt();
}
}
function Person(name) {
this.name = name;
}
Person.prototype.greet = function() {
return 'Hello, ' + this.name;
}

function Employee(name, salary) {
Person.call(this, name);
this.salary = salary;
}
Employee.prototype = new Person();
Employee.prototype.constructor = Employee;
Employee.prototype.grantRaise = function(percent) {
percent /= 100;
this.salary += (this.salary * percent).toInt();
}
Operator "overloading "
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 23/35
class Hug {
num strength;
Hug(this.strength);

Hug operator +(Hug other) => new Hug(strength + other.strength);
}
main() {
var hug1 = new Hug(10);
var hug2 = new Hug(100);
var bigHug = hug1 + hug2;
}
// not supported
Finding elements in DOM
Find one element by id
querySelector('#main');
document.getElementById('main');
document.querySelector('#main');
Find one element by class
querySelector('.visible');
document.getElementsByClassName('visible')[0];
document.querySelector('.visible');
Find many elements by class
querySelectorAll('.visible');
document.getElementsByClassName('visible');
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 24/35
document.querySelectorAll('.visible');
Find one element by tag
querySelector('div');
document.getElementsByTagName('div')[0];
document.querySelector('div');
Find many elements by tag
querySelectorAll('div');
document.getElementsByTagName('div');
document.querySelectorAll('div');
Find one element by name
querySelector('[name="form"]');
document.getElementsByName('form')[0];
document.querySelector('[name="form"]');
Find many elements by name
querySelectorAll('[name="form"]');
document.getElementsByName('form');
document.querySelectorAll('[name="form"]');
Find elements by combination of above
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 25/35
querySelector('#main').querySelector('div').querySelectorAll('.visible');
querySelectorAll('#main div:first-of-type .visible');
document.getElementById('main').getElementsByTagName('div')[0].getElementsByClassName('visible');
document.querySelectorAll('#main div:first-of-type .visible');
Iterate over a list of elements
for (var el in els) {
doSomethingWithEl(el);
}
for (var i = 0, el; el = els[i]; i++) {
doSomethingWithEl(el);
}
Access the first child
elem.children.first;
elem.children[0];
elem.firstChild();
Find out whether an element has children elements
!elem.nodes.isEmpty;
elem.hasChildNodes();
Manipulating DOM
Create an element
import 'dart:html';
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 26/35
var element = new Element.tag('div');
// Many elements have their own constructors.
var element = new DivElement();
var element = document.createElement('div');
Create an element and set its contents
var element = new Element.html('<p>A quick brown <em>fox</em>.</p>');
var element = document.createElement('p');
element.innerHTML = 'A quick brown <em>fox</em>.';
Add an element to a parent
element.children.add(newElement);
element.appendChild(newElement);
Remove an element from its parent
element.remove();
element.parentNode.removeChild(element);
Regular expressions
var email = 'test@example.com';
(new RegExp(r'@')).firstMatch(email);
// == Match Object
var email = 'test@example.com';
email.match(/@/);
// == ['@']
var invalidEmail = 'f@il@example.com';
(new RegExp(r'@')).allMatches(invalidEmail)
// == Iterable Match Object
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 27/35
var invalidEmail = 'f@il@example.com';
invalidEmail.match(/@/g)
// == ['@', '@']
Exceptions
Throw an exception
throw new Exception("Intruder Alert!!");
// You can also throw strings
throw "Unexpected user input";
throw new Error("Intruder Alert!!");
// or...
throw "Intruder Alert!!";
Catch an exception
main() {
try {
int.parse("three");
} on FormatException catch(fe) {
print("Ouch! Detected: $fe");
} catch(e) {
print("If some other type of exception");
} finally {
print("This runs even if an exception is thrown");
}
}
try {
undefinedFunction();
} catch(e) {
if (e instanceof ReferenceError) {
console.log('You called a function that does not exist');
}
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 28/35
} finally {
console.log('This runs even if an exception is thrown');
}
DOM Event handling
Attach an event handler
element.onClick.listen(handleOnClick);
handleOnClick(Event e) {
// ...
}
// Or, if the handler does not take an event
element.onClick.listen((e) => subscribeToService());
element.addEventListener('click', handleOnClick, false);
Remove an event handler
var subscription = element.onClick.listen(handleOnClick);
subscription.cancel();
element.removeEventListener('click', handleOnClick, false);
Timing
Schedule a future event
import 'dart:async';
var timer = new Timer(new Duration(milliseconds:500), () { });
setTimeout(function() { }, 500);
Measure the execution time of a function
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 29/35
int measure(fn) {
var watch = new Stopwatch();
watch.start();
fn();
return watch.elapsedMicroseconds;
}
function measure(fn) {
var start = Date.now();
fn();
return Date.now() - start;
}
HTML attributes
Get HTML attribute
element.attributes['href'];
element.getAttribute('href');
Set HTML attribute
element.attributes['playable'] = true;
element.setAttribute('playable', true);
Remove HTML attribute
element.attributes.remove('playable');
element.removeAttribute('playable');
Check if HTML attribute exists
element.attributes.containsKey('href');
element.hasAttribute('href');
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 30/35
CSS classes
Add CSS class
element.classes.add('new-class');
element.className += ' new-class';
element.classList.add('new-class');
Remove CSS class
element.classes.remove('new-class');
element.className = element.className.replace(/ new-class/, '');
element.classList.remove('new-class');
Request data via XMLHttpRequest
HttpRequest.request("/data.json").then((req) {
print("The contents of your data: ${req.responseText}");
});
var client = new XMLHttpRequest;

client.onreadystatechange = function() {
if (this.readyState == 4) {
processData(this);
}
}
client.open('GET', 'data.json');
client.send();
function processData(request) {
console.log('The contents of your data: ' + request.responseText);
}
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 31/35
jQuery
React to document finishing loading
window.onContentLoaded.listen((e) => print('Content is loaded'));
// However, main() will normally run after DOMContentLoaded
$(document).ready(function(){
console.log('Content is loaded');
});
Node lookup
var els = querySelectorAll('div');
var els = jQuery('div');
Node creation
var pic = new Element.tag('img');
pic.classes.add('avatar');
pic.classes.toggle('main');
pic.attributes['src'] = 'myPic.jpg';
// Or:
var pic = new ImageElement('myPic.jpg');
pic.classes
..add('avatar')
..toggle('main');

// Cascades (..) allow you to chain
// multiple method calls on an object.
document.body.children.add(pic);
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 32/35
var pic = $('<img/>');
pic.addClass('avatar');
pic.toggleClass('main');
pic.attr('src', 'myPic.jpg');
$('body').append(pic);
Event handling
querySelectorAll('a.person').forEach((el) {
el.onClick.listen((e) => print('Person clicked'));
});
$('a.person').click(function(e){
console.log('Person clicked');
})
Relative nodes
var myNode = querySelector('div');
var parent = myNode.parent;
var next = myNode.nextNode;
var myNode = $('div:first');
var parent = myNode.parent();
var next = myNode.next();
Children
var myNode = querySelector('div');
if (!myNode.children.isEmpty) {
myNode.children.clear();
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 33/35
}
var myNode = $('div:first');
// If there are children, remove them
if (!myNode.is(':empty')) {
myNode.empty();
}
Clone
var clonedElement = querySelector('#about').clone(true);
var clonedElement = $('#about').clone();
Absolute value
-4.abs() // == 4
Math.abs(-4) // == 4
Ceiling
4.89.ceil() // == 5
Math.ceil(4.89) // == 5
Floor
4.89.floor() // == 4
Math.floor(4.89) // == 4
Random
import 'dart:math';
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 34/35
var rand = new Random();
// Returns a random double greater than or equal to 0.0
// and less than 1.0
rand.nextDouble();
// Returns a random boolean value.
rand.nextBool();
// Returns a positive random integer greater or equal
// to 0 and less than 10
rand.nextInt(10);
// Returns a random float greater than or equal to 0.0
// and less than 1.0
Math.random()
Sine and Cosine
import 'dart:math' as Math;
sin(Math.PI/2) // == 1.0
cos(Math.PI) // == -1.0
Math.sin(Math.PI/2) // == 1
Math.cos(Math.PI) // == -1
Convert a String to a number
int.parse('3') // == 3
double.parse('3.14') // == 3.14
int.parse('3px') // ERROR: throws FormatException
int.parse('three') // ERROR: throws FormatException
parseInt('3') // == 3
parseFloat('3.14') // == 3.14
2/5/2014 Synonyms - Dart, JavaScript, C#, Python | Dart: Structured web apps
https://www.dartlang.org/docs/synonyms/ 35/35
parseInt('3px') // == 3
parseInt('three') // NaN
Run-time program manipulation
// Dart doesn't support eval(). This is not a bug.
eval('alert("hello from eval")');
Adding a method to a class
// Dart doesn't support changing a class after
// the program has been compiled
String.prototype.startsWith = function(beginning) {
var head = this.substr(0, beginning.length);
return head == beginning;
}

Vous aimerez peut-être aussi