Ajax

Asynchronous Javascript And XML

origin

var api = 'https://api.github.com/users/xudafeng';

var xmlHttp = new XMLHttpRequest();

xmlHttp.open('GET', api, true);

xmlHttp.onreadystatechange = function(d) {
  if (xmlHttp.readyState == 4) {
    console.log(xmlHttp.responseText);
  }
};

xmlHttp.send(null);

jQuery

var api = 'https://api.github.com/users/xudafeng';

$.ajax({
  method: 'GET',
  url: api,
  data: {
    foo: 'bar'
  }
}).done(function(msg) {
  console.log(msg);
});

JSON

JavaScript Object Notation

JSONP

JSON with Padding

Reference

  1. JSON
  2. jQuery.ajax
  3. MDN, Using_XMLHttpRequest

commonjs

namespace

var bar = function() {
  console.log('bar');
};

bar();

var obj = {
  foo: function() {
    console.log('foo');
  }
};

obj.foo();

closure

start with closure

(function() {
  console.log(this)
})()

module.exports

module.exports = function() {
  console.log('foo');
}

exports

exports.foo = function() {
  console.log('bar');
}

AMD

define(function(require, exports, module) {
  var foo = require('foo');
  var bar = require('bar');

  console.log(foo);
});

webpack

Reference

  1. commonjs
  2. webpack

event

publish/subscribe

var EventEmitter = require('events').EventEmitter;

var foo = new EventEmitter();

foo.on('bar', function(d) {
  console.log(d)
});

foo.emit('bar', {
  data: 'data'
});

Reference

  1. nodejs, events

style

2 Spaces for indention


function() {

  // right
  var foo = 'bar';

  // wrong
    var foo = 'bar';
}

Use Semicolons

// right
var foo = 'bar';

// wrong
var foo = 'bar'

80 characters per line

Use single quotes

// right
var foo = 'bar';

// wrong

var foo = "bar";

Opening braces go on the same line

// right

if (true) {
  console.log('winning');
}

// wrong

if (true)
{
  console.log('losing');
}

Declare one variable per var statement

// right

var keys = ['foo', 'bar'];
var values = [23, 42];

// wrong

var keys = ['foo', 'bar'],
values = [23, 42];

Use the === operator


// right

if (foo !== 1) {
  console.log('bar');
}

//wrong

if (foo != 1) {
  console.log('bar');
}

Reference

  1. node-style-guide
  2. Airbnb, javascript