Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Monday, November 23, 2015

MomentJS Notes

Install

npm i moment --save
npm i moment-timezone --save

Use

var moment = require('moment-timezone');

Create moments in and out of DST:

var cdt = moment.tz("2015-07-23 08:30", "America/Chicago");
var cst = moment.tz("2015-11-23 08:30", "America/Chicago");

Check that offset from UTC is what you'd expect:

cdt.tz('America/New_York').format()
> '2015-07-23T09:30:00-04:00'
cst.tz('America/New_York').format()
> '2015-11-23T09:30:00-05:00'

Check that zone aware format output is what you'd expect:

cdt.tz('America/New_York').format('HH:mm:ss')
> '09:30:00'
cst.tz('America/New_York').format('HH:mm:ss')
> '09:30:00'


Saturday, October 31, 2015

My Ideal Full Stack JavaScript Team Environment

Here are some of the tools and practices that I'm currently in favor of when working in a team environment on a JavaScript Full Stack project. In no particular order.

Pull Requests


All code should have a second set of eyes on it at some point. This serves the following purposes:

1. Catch bugs or potential bugs.
2. Teach both the reviewer and reviewee.
3. Keeps the team members up-to-date with what other teams members are working on.
4. Introduces best practices, new features/techniques and new libraries.

PRs should almost always be assigned to someone. Others can be @mentioned. Almost anyone (senior enough) should be able to signed off with a Looks Good To Me (LGTM) in the comments and merge.

The developer submitting the PR should let the reviewer know the urgency of the PR.

1. Urgent. The submitter immediately accepts the PR. The review is done post-facto as a learning and review process. Can also catch bugs that are fixed in the next PR.
2. Normal: Someone is expected to review this within an hour.
3. Low: Review within the next day.

Linting


An automated linting tool should be part of the commit process. Locking in lint errors to a maximum value will allow the gradual introduction of linting to existing projects.

My default (and currently the mostly popular) linting tool for JavaScript projects is ESLint.

Developers should be encouraged to have a lint helper plugin in their editors so they rarely/never see lint errors on commit.

The team should have an evolving .eslintrc file that's shared across all projects. Some projects might have specific override .eslintrc rules if they are catching up with the standard or have exceptions.

Keep the master .eslintrc in a dot-files folder that's a sibling of all the other projects and reference it from there.

ES6


ES6 is here. There are very few reasons not to start using this. Babel is an excellent transpiler that will allow developers to start using those features.

Use code reviews to help teach other team members ES6.

If you're not using ES6 you'll start leaking developers to other teams and companies. More on this below...

Hot Loading


Most projects should have tooling setup so that they can quickly iterate on small changes to code that they are working on and see the results.

This rapidly accelerates both learning and development.

If, for example, you're working on a React/Node project then, in my opinion, you'd have the Webpack Hot Module Replacement transpiling your changes in memory and making them almost instantly available in the browser.

As developers we're always on a learning curve. We can never be expected to know everything. Using a fast responsive hot loader we can quickly try different techniques and see the results. This will speed our learning of how that corner of the world works.

Front End Framework

Most projects should be using a modern front-end framework for the UI component. The most popular over the last several years has been AngularJS. The current rising start is ReactJS.

I'm in favor of ReactJS. It looks like AngularJS and EmberJS are converging on what ReactJS has introduced.

Latest Versions


We should strive, as much as possible, to be using the latest versions of everything. It's perfectly acceptable to hold off on the brightest and shiniest until it's stable. That should be a conscious decision and not the default.

Npm has a great command npm outdated --depth 0 that will give us a summary of how our project looks compared to what's available. Use that command with the -g option to check your globally installed tooling.

The 3 main reasons usually given for keeping up with the latest version (1. Features 2. Performance 3. Bug Fixes) are completely irrelevant. The reason you want to stay current is to keep your developers happy and engaged. Nobody wants to work on yesterday's technology.

Keeping a buzz in the team about moving to the next version will keep everyone up-to-date on what's happening and engaged with the team. The grass-is-greener syndrome with other teams or companies won't exist on the technology front because you'll be using the latest. In fact I've successfully used this as a recruiting tool for developers who are stuck in other companies or teams on old technology.

Related:

Your tooling should automatically keep your project's dependencies up-to-date with what would be installed when someone initially installs the dependencies on the project. I use the npm-update-outdated module as part of my pre-commit hook to update my dependencies before the tests are run so I know that my tests have run against what the CI server will use.

Project Onboarding


If someone asks you to work on a project then you should be able to do the following pretty quickly.

1. git clone
2. npm install
2. npm test (should run clean)
4. npm start

And have a server up and running that the browser can hit and interact with.

There are lots of complexities that might stop something that simple from working.

The project's readme should have bullet proof (as good as possible) instructions on how to address that.

For example, most developers have Docker. If you have a dependency on a MongoDB then npm start or npm install should run Docker and pull down a MongoDB container and get it up-and-running.

A new-to-the-project developer who experiences problems with an out-of-date README.md and who then updates the README.md should be given the rest of the day off as a reward. (That might be a bit extreme. This almost never happens so it might also be okay.)

Testing

All projects should have tests. These should run during a pre-commit hook. Ideally these are run implicitly through the Code Coverage tool.

When bugs are fixed a test should usually be written demonstrating the bug before it's fixed. This test will prevent a regression on this bug later.

Tests are difficult to write. Do lots of cross-education with other team members during PRs with tests. Get to know and love all the tooling around tests. When you're using a tool for the first time ask for help and opinion in the PR.

Some of the tools I use for testing:

Code Coverage

Code coverage such as Istanbul can be automated as part of a pre-commit hook. It will help make sure that critical sections or sections that you're about to change have sanity tests. It has awesome "graphics"

Code Coverage Minimum Levels


It's easy for a developer to commit new code that doesn't have test coverage. In my enthusiasm to get my new code out there I often forget to write tests for it. Using a tool like Istanbul we can prevent code coverage from dropping from the previous level in a pre-commit hook. This will remind us that we need to add tests.

Update 11/2/15


Isomorphism


I didn't used to think that isomorphic JavaScript was that important. I believe that it is now becoming important.

Least of all you should never have duplicate code that's duplicated for the sake of using on both server and client. There is almost always a way to provide the same code block to both client and server to provide a DRY and isomorphic code-base.

Tuesday, September 22, 2015

ReactJS JSX gives us HTML in JavaScript

What I consider the main difference between ReactJS and its JSX syntax when compared to the other frameworks like AngularJS, EmberJS, and BackboneJS is that JSX is HTML in JavaScript. The others have JavaScript in the HTML.

HTML-in-Code instead of Code-in-HTML.

Here's a simple example:




React's JSX:

myCollection.map( (item) => {

  return render (

    <div>{item}</div> 

  );

});


AngularJS:

<div ng-repeat="item in myCollection">

  <div>{{item}}</div>

</div>

One of the things that we continuously struggle with is the ability to program markup. To do this we've been adding language to the markup.

JSX stands that paradigm on its head and adds the markup to the language.

As a developer I enjoy writing code more than writing markup. JSX means that I don't have to jump-out-of the markup to make things happen to it. The markup is encapsulated inside the logic that controls the flow of the application.

With AngularJS I'm consciously wiring language and markup together.

AngularJS appeals to the designer in me while JSX appeals to the developer in me.

I'm not against AngularJS or the other frameworks. I enjoy writing code and solving hard problems. I also hated the sight of JSX when I first saw it and before I wrote my first project in it. It didn't seem right to pollute JavaScript with markup.

For me the AHA moment was the productivity I felt that React gave me by keeping me in my area of expertise: JavaScript. I'm good at HTML and CSS. I'm an expert at JavaScript. More productivity happens in your area of expertise.

Long live ReactJS.
Long live AngularJS.



Tuesday, September 15, 2015

Moving your Team and Project to ES6

How do you safely move your team to using ES6?



1. Convince the team/boss/stakeholders that it's time to move to ES6


The points in this article might help.

2. Decide what you're going to use


Are you going to use a transpiler like Babel or a shim? If using Node.js are you going to use the --harmony flag? There are plenty of articles that discuss this.

3. Start using ES6


Most teams will have at least one person who wants to use the new syntax. This is how these developers should introduce ES6 to the rest of the team.

Training? That's one way. Another is to cross-train each other on a code base that you're already working on.

Let's say that you wrote some ES5 code like this:

handleChange(name, e) {
  var change = {};
  change[name] = e.target.value;
  this.setState(change);
}

and you decided that you'd rather use ES6 syntax like this:

handleChange(name, e) {
  var change = {
    [name]: e.target.value;
  }
  this.setState(change);
}

The better way to use the ES6 syntax is to tag it with the name of the new feature like this:

handleChange(name, e) {
  var change = {
    // ES6: Destructuring, computed property keys
    [name]: e.target.value;
  }
  this.setState(change);
}

A developer looking at the ES6 comment should be able to copy/paste the text into a search engine and find a reasonable list of articles that deal with the feature.

4. Teach in the Pull Request Review


Now when you do a Pull Request on your changes message the rest of the team that there are labeled ES6 features.

I've found that this has the extra bonus of having more developers want to review your code because they know that they're going to be learning something new about ES6 during the review process.

Your team are already contributing to and editing a code-base that they're familiar with so the ES6 usage that they're learning is not contrived. It's real world.

5. Remove the ES6 comments


The comments labeled ES6: are there for training purposes. After a period of time you may want to remove them. This is easy to do in a search and delete of this type of comment in the code base.

If you have a lot of non-ES6 developers continually joining the project then you might not want to do this. You can also tag the repository before removing the comments so others can checkout that tag and read the comments.

You might also elect to start dropping comments for the easy-to-understand and common ES6 features and keep them in for the more complex scenarios.

Wednesday, March 25, 2015

Should I use Extend or Assign in Lodash?

 

 

Use _.assign()


Justification

 

  1. If you look at the lodash documentation for _.assign() you'll see that _.extend() is an alias for _.assign(), not the other way around. This would imply that _.assign() is the default and _.extend() is an alternative.
  2. ECMAScript 6 will use assign() and not extend().

Saturday, September 20, 2014

Node.js Workshop with HTTP Status Check

I've been using HTTP Status Check for Node.js Workshops to help coach developers wanting to learn or get better at Node.js and JavaScript development.

HTTP Status Check is a Node.js utility that takes a list of URLs and checks that their statuses and other properties are what you would expect. As a web developer we usually have a number of domains, URLs and sites that we need to "keep-an-eye" on and this utility will quickly check the health of all our sites and report it back to us.

The benefits of using this project for a workshop are:
  • Most Node.js development is around web development. As a web developer you need to know and understand the HTTP protocol. This utility is all about that.
  • It's small and easy to understand.
  • It's something that you can (and should) use each day to keep an eye on your web properties. This means that you'll directly benefit from any changes you make to it.
  • Which brings us to changes. It's easy and quick to make changes in your fork (branch) of the project if you need it to do more than what it currently does.
  • In addition to learning Node.js/JavaScript you get to learn how to use Git, GitHub, Npm, how to contribute to Open Source and how to build your reputation and resume on GitHub.
To get the most out of a workshop you need your laptop to be in a state that allows you to dive in and start learning Node.js and JavaScript. This means that you need some basic applications installed and accounts setup and configured. Before attending, do the following. If any of the steps are unclear then post a comment below and I'll clarify.

("repo" is short for repository or code-repository. The code that you run is in a repo and you will pull it down to your machine. More on that to come...)
  1. Setup a GitHub account and log into it: https://github.com/join
  2. Fork the HTTP Status Check repo. (Forking is the process of making a copy of the code-base in your GitHub account that you have complete control over to do with as you please.)
    1. You must be signed into GitHub. Go to the repo: https://github.com/guyellis/http-status-check
    2. If you're signed in then you will see some buttons towards the top right of the page: Watch, Star, Fork. Click on the Fork Button.
    3. The repo will now be forked (copied) to your account and you will be redirected to it, something like: https://github.com/<your-account-name>/http-status-check
    4. Congratulations, you've successfully forked your first GitHub project and taken your first step to contributing to open source.
  3. Install Git on your computer. You now need to get that repo (the code-base) from your fork on GitHub to a directory on your computer. This is done through a process called cloning which as the name suggests creates a clone of your fork on your local machine. Before we can do this though we need to install Git:
    1. Use the official Git download page to find and install the right Git Client for your OS: http://git-scm.com/downloads
    2. There is also a link on that page that will take you to popular Git GUI clients.
    3. Once that's done come back here.
    4. Open a command window and type git and hit enter. You should be presented with a list of git commands. This confirms that git has been successfully installed.
  4. Clone the repo.
    1. Create a directory where you want to keep your source code. You don't need to create a directory for the HTTP Status Check project, just one that will hold your projects. For example /source/ or /code/ or /myrepos/ or something like that.
    2. Now open a command window in that directory or open a command window and change to that directory.
    3. Clone the repo by executing this command after you have replaced your-github-account-name with your GitHub account name. (This is where you forked the repo to in the Fork step above.):
      git clone https://github.com/<your-github-account-name>/http-status-check.git
      • Some notes about this:
      • You can find the correct link to use on your GitHub page by looking at the forked repo and on the right hand side you'll see something that says HTTPS clone URL. Right below that is a text box that you can copy the link from.
      • If you want to use SSH then you can click the SSH link below that box to switch the link to the correct SSH link.
    4. If this is successful then you'll see something that looks like this. The numbers that you see will be different:

      Cloning into 'http-status-check'...
      remote: Counting objects: 395, done.
      remote: Total 395 (delta 0), reused 0 (delta 0)
      Receiving objects: 100% (395/395), 56.90 KiB | 0 bytes/s, done.
      Resolving deltas: 100% (224/224), done.
      Checking connectivity... done.
    5. A directory would have also been created for you called http-status-check.
  5. Code Editor. You need a code editor to edit the code that you've just cloned. If you don't already have one installed then try one of these which are available on almost all Operating Systems:
    1. WebStorm: 30 day trial and then $49 to buy and $29/year renewal after that (for non-commercial use).
    2. Sublime Text: Free evaluation and then a $70 single payment for continued use.
  6. Install Node.js and Npm. I deliberately put this step at the end. I want you to be able to immediately run something after you've installed Node.js and see it in action which is why you got the code setup first.
    1. Go to the Node.js site and install it for your Operating System. This will also install Npm which you'll need later.
    2. Once installed open a command window and change directory to the HTTP Status Check directory and run node.
    3. You should see a > command prompt. This confirms it was installed. Hit Ctrl+C twice to exit.
  7. Run Npm. 
    1. In the same command window in the http-status-check directory run npm install. (You can also run npm i which is a shorter version of this.)
    2. You should now see all the dependencies being downloaded and added to the project. Here is an example of some of what you'll see in the console window. Some of the numbers might be different:

      debug@2.0.0 node_modules/debug
      └── ms@0.6.2

      chai@1.9.1 node_modules/chai
      ├── assertion-error@1.0.0
      └── deep-eql@0.1.3 (type-detect@0.1.1)

      lodash@2.4.1 node_modules/lodash
  8. Run HTTP Status Check.
    1. Now type node index.js and hit enter and the HTTP Status Check utility will run. You should see something like this:

      _ Google (http://google.com) testing disabled.
      _ HTTP Status Check on Guy's Blog (http://www.guyellisrocks.com/2014/06/http-status-check.html) working as expected.
      _ Missing URL example (http://www.guyellisrocks.com/2014/06/will-this-get-written.html) working as expected.
      _ LinkSilk WWW (http://www.linksilk.com) working as expected.
      _ LinkSilk (http://linksilk.com) working as expected.
      A total of 5 URIs were tested.
      Failure count:  0
      Success count:  4
      Disable count:  1
  9. Done! You've successfully forked, cloned, installed and run your first Node.js application. Now you're ready to start making changes to it to customize how it works. We'll cover code changes in the workshop. In the mean time you can change the list of web sites that it checks to check your sites and immediately provide you with some value:
    1. Copy the samplesites.js file (in the root of the project) to a file called checksites.js. (checksites.js will take precedence over samplesites.js if it is present.)
    2. Edit the checksites.js file and replace the sample web sites with your own websites and rules. The file is heavily commented (lines starting with // are comments) to guide you to what changes you can and should make.
    3. Now run node index.js again and you'll see your sites being checked.
  10. Workshop and Questions. If you weren't able to get to this point then post comments to this blog post. You should also bring your questions to the workshop. If you're not able to edit your checksites.js file and run it against your sites before the workshop then you'll miss out on making changes to the code and learning about Node.js and JavaScript.

Bonus Tasks

  1. Run the tests.
    1. In a console window in the http-status-check directory run npm test.
    2. All the tests should pass.
  2. Run code coverage.
    1. In a console window in the http-status-check directory run npm run istanbul.
    2. The tests will run (as above) and code coverage will be calculated. The output should end with something that looks a little bit like this:

      Statements   : 100% ( 170/170 )
      Branches     : 88.73% ( 63/71 )
      Functions    : 100% ( 23/23 )
      Lines        : 100% ( 169/169 )
    3. Now open the coverage/lcov-report/index.html file that was created as a result of this and look at how the tests cover the solution.
  3. Learn more about how Git and GitHub work. Install Ungit and use its graphical interface in the browser to visual understand the repo's structure and work with the repo.
  4. New features in HTTP Status Check.
    1. Is there a bug that needs to be fixed or feature that you think should be added to HTTP Status Check? Then add it as an issue: HTTP Status Check Issues. (Even if you intend to work on this you should add it to the issues first and then assign it to yourself.)
    2. Want to work on existing issues in HTTP Status Check. Then find them in the same place: HTTP Status Check Issues

Tuesday, June 3, 2014

JavaScript Dependency Injection.

Using JavaScript Dependency Injection for Spies, stubs and mocks in unit testing.

I was in the process of picking a Dependency Injector for use in a project in JavaScript. My default to narrow down the top three is to use Google as my initial search and then GitHub's star count as the top-three filter and then compare the features that I need.

After looking a SinonJS, sandboxed-module, rewire, and proxyquire I decided to be slightly more analytical and objective about how I compared them. I decided to include the Watch and Fork count in addition to the Star count. I created a spreadsheet that compared them:
 

watch star fork Avg
rewire 20 425 16 0.48
sinon 52 1471 233 2.08
sandboxed 10 190 24 0.29
proxyquire 2 195 12 0.15

84 2281 285 3

I averaged the modules giving each of the attributes a one third weighting. Given that starring is 27 times more common than watching you might question this weighting. I justify it because starring is a less costly action (no update emails) and more likely to do than watching.

Seeing this as a pie chart makes this information easier to absorb. The clear winner amongst these four modules is SinonJS with almost three-quarters of the attributes.







Wednesday, December 11, 2013

How many Friday 13ths in a Year in JavaScript

Inspired by a code golf question on codegolf.stackexchange.com asking for code that counted the number of Friday 13ths in a year I came up with this inefficient NodeJS/JavaScript solution. Both the solutions below can be dropped into a .js file and run from the command line by NodeJS.

// To run:
// node friday13.js <2013>
// <2013> is the year which you want a count of Friday 13ths in

// Add a day incrementer to the Date prototype
Date.prototype.addDays = function (num) {
    var value = this.valueOf();
    value += 86400000 * num;
    return new Date(value);
}

var year = process.argv[2];
if(!year){
 console.log('Was year the first param? Received: ' + year);
 return;
}

var startDate = new Date(year,0,1);
console.log(startDate);

var endDate = new Date(year,11,31);
console.log(endDate);

var counter = 0;
while(startDate <= endDate) {
 if(startDate.getDay() === 5 && startDate.getDate() === 13) {
  counter++;
 }
 startDate = startDate.addDays(1);
}

console.log(counter + ' Friday 13ths in ' + year);

Someone else came up with another JavaScript solution which takes advantage of some of the idiosyncrasies of JavaScript which I thought was interesting:

var year = process.argv[2];

var numFridays = function(year) {
 var count=0;
 for(month=12;month--;) {
  count += !new Date(year,month,1).getDay();
 }
 return count;
}

console.log('Number: ' + numFridays(year));

Here are the interesting parts:
  1. The for loop on line 5 relies on the fact that when the value of month hits zero it will evaluate to false.
  2. On line 5 month will be evaluated for truthiness before it's decremented and that it will be decremented before the body of the for loop is evaluated.
  3. We only have to loop through the 12 months of the year as there can only be one Friday 13th in each month so no need to go through every day.
  4. The JavaScript getDay() method of the Date object returns a 0 for Sunday, 1 for Monday etc. If the month has a Friday 13th then by definition the first day of the month is a Sunday. i.e. if the value of getDay() on the 1st of the month is 0 (equivalent to false) then count this month. To do that we ! (not) the return value which gives us true which will evaluate as the value of 1 when added to an integer.

Thursday, December 5, 2013

Understanding ES6 Fat Arrows

I'm going to try and do this explanation by manipulating a very simple line of code and transition an anonymous function to a fat arrow function.

[1,2,3].map(function(x) { return x + 1;});

Switch (swap) function and (x):

[1,2,3].map((x) function { return x + 1;});

This does not work. Just showing that you switch the word "function" with the parameter: (x)
Replace function with => (a fat arrow). You end up with this.

[1,2,3].map((x) => { return x + 1;});

Use Firefox if you want to test this as the fat arrow function hasn't been implemented in Chrome yet.

Tuesday, December 3, 2013

Full stack JavaScript is not about sharing code front to back



I'm watching a panel discussion at Node Summit and noticed one of the panelists saying that they found that there was very little benefit to sharing code between the front and back end when developing in a JavaScript full stack environment.

Recently I was touting the virtues of NodeJS and the person I was speaking to said "in reality how much code can you share across the stack?" I had to point out that this was not a virtue that I extolled and I've never thought of this to be a benefit of JS full stack.

In my opinion, shared code across the stack is a bonus and not a benefit. The primary benefit comes from the synergies and efficiencies in working in a single language through the stack. This means that if someone who traditionally worked on the front end has to dive in and do some work on the back end they are not going to be shocked by a different syntax and instead will be somewhat comfortable with what they see.

Wednesday, October 2, 2013

A Dozen JavaScript Libraries

Just spent a couple of hours this evening listening to Rob Richardson give an awesome presentation on A Dozen JavaScript Libraries.

He covered:
  1. jQuery
  2. Lo-Dash
  3. Handlebars
  4. Modernizr
  5. Moment
  6. Normalize.css
  7. Twitter Bootstrap
  8. jQuery UI
  9. Backbone
  10. Angular
  11. JSHint
  12. Jasmine
  13. RequireJS
  14. Rafael
in enough detail to arm you with the ability to select one of them for a future project. It also looks like he's extended the Baker's Dozen (13) metaphor to a JavaScript Dozen (14). I'm guessing that JavaScript has the math library to do that.

Also love that he's using reveal.js for his presentations.

Good work Rob!

Friday, July 26, 2013

OSCON Clientside MVC

The Clientside MVC page on the OSCON site

Tom Cully (BigCommerce Ltd Pty)
11:50am Friday, 07/26/2013

http://mozart.io/

Clientside MVC provides:
- scalability
- clientside apps exist mostly as static assets allowing greater use of CDN tech

SEO Problem
- webcrawlers and other automated clients that don't run JS
- implementing graceful degradation is possible...
- only early solutions exist e.g. Mozart Concerto

BigCommerce created Mozart to address their deficiencies in the other MVC frameworks. Mozart is written in CoffeeScript.

BigCommerce currently have their Operation Slick running in A/B testing with a 60% probability that a customer will get it at this point.

Mozart Demos
todomvc.com

github.com/tomcully/mozart

HTML5 Unreal Engine

Thursday, July 25, 2013

OSCON Developing full stack Javascript applications

The Developing full stack Javascript applications page on OSCON

Grant Shipley (Red Hat)
5:00pm Thursday, 07/25/2013

IaaS, PaaS, SaaS

PaaS example: OpenShift

OpenShift is free (will pay for EC2 time)

SampleApp will have:
strongloop
mongodb
twilio
openshit
appcelerator (titanium)
- eclipse based ide
- integrated with OpenShift
- build, test and deploy mobile apps from a single ide
- debugger

https://github.com/gshipley/OSCON2013

created a templated app in titanium studio
standardized on commonJS
















OSCON New Rules For JavaScript

The New Rules For JavaScript page on OSCON site.

Kyle Simpson (Getify Solutions)
4:10pm Thursday, 07/25/2013

54y.geti.fi/slides/js-rules/oscon

Kyle is writing youdontknowjs.com

html5hub.com

linters - jslint, jshint, eslint
- use for checking and agreeing on style

stop thinking JS (as a dynamic language) doesn't have types

!! same as Boolean(a)

7 types:
null, undefined, boolean, string, number, object, function
can get type by using typeof  except for null which will return object

stop thinking JS variables have types

values have types, and those types can't change but vriables can hold any value at any time

== allows coercion
=== disallows coercion

null == undefined // true

stop using anonymous functions
- improves readability of stack when debugging
- also name IIFE
- named functions are always better

don't assume the JS engine optimizes away mistakes

stop abusing function scope

block scoping is better than manually hoisting variables

 let() {}
- does not exist yet
- can use blockscope.js on GitHub

 stop using this until you really understand how it gets assinged
is the call-site new-invoked? use that
is the call-site binding overriden with call/apply?
... add more from slides

stop using new Something() "constructors" to "instantiate" ...

OO vs OLOO (Objects Linked to Other Objects)
class vs delegation oriented code

delegation oriented programming

OSCON Adventures in Node.js

The Adventures in Node.js page on OSCON.

Faisal Abid (Dynamatik, Inc.)
2:30pm Thursday, 07/25/2013

node.js is built around "events"
event loop is always running checking for new events
fires callbacks when new events are received

http.createServer(function(request, response) {
    // request has all information about request
    // response allows packaging of what will be returned to client.

}

use EventEmitter class to write custom events
 - can help with callback hell

require is used to import modules to your application.
- modules are like classes
- http module is stored in the node_modules folder
- require returns a JSON object

in examples using nodemon

npm is used to get modules
npm.org -
run from cmd line:
npm install socket.io
npm install nodemon
npm install -g coffee-script

package.json is a manifest for node
"npm install" will read package and work out and download required packages
use * in package to get latest version otherwise specify version number
npm install --save hbs - adds to package.json?

Express.js
- framework like sinatra
- REST API for node
- great support for templates
- templates: Jade, EJS, Dust (LinkedIn now owns Dust)

restangular - simplify rest on angular

node has 32k modules out there, huge community support

OSCON Deal with multiple types of input in your HTML5/JavaScript code

The Deal with multiple types of input in your HTML5/JavaScript code page at OSCON.

Olivier Bloch (Microsoft)
11:30am Thursday, 07/25/2013

Pointer Events

average finger width
threshold for finger is 11mm which is 40px

avoid hiding content behind :hover

use HTML5 input types
switches keyboard based on input type

Pointer Events
an event model for touch, pen, mouse, and more
- simplicity of mouse events
- with support for multiple device types
including multi-touch (even multi-user)
device-specific peroperties like pressure or touch contact size
hand.js - pointer events pollyfill

touchcontrol.js
example of single canvas with virtual joystick

Example of node server communicating with copter

resources:
w3.org/TR/pointerevents/
bit.ly/win8touchguidance
docs.webplatform.org/wiki/concepts/PointerEvents
github.com/jacobrossi/PointerPaint/










OSCON Getting Started with 3D Programming in Three.js

The Getting Started with 3D Programming in Three.js page on OSCON site.

Chris Strom (EEE Computes), Robin Strom (EEE Computes)
10:40am Thursday, 07/25/2013

gamingjs.com/ice is sample site.

Book: 3D Game Programming for Kids - Create Interactive Worlds with JavaScript

Three.js
Low Complexity (for dummies)
Lightweight JS Library
Modern browsers
Canvas, SVG, CSS, and WebGL

Code-a-long with above ice editor

esh: Core 3D Object
combination of
Shapes -

Animation
requestAnimationFrame()
- callback to update the scene
- stube for window.requestAnimationFrame(), if available.

The power of add()-ition
with add()
group object together
create a new frame of reference

WebGL vs Canvas
WebGL is better
nicer graphics
beter animation
bettera meterial
better effects
Canvas is better support

Physics with Physisja
dropin replace for three.js

Wednesday, July 24, 2013

OSCON Translated Strings and Foreign Language Support in JavaScript

The Translated Strings and Foreign Language Support in JavaScript Web Apps on the OSCON site.

Ken Tabor (Sabre Holdings)
5:00pm Wednesday, 07/24/2013

Translating:
what - date/time formatters
where - single page app

Basic solution
- string table, disconnects string from code

Never hard code text string
string-tables must be easily accessed throught the application
language string-tables must be demand-loadable resource.

- Combine duplicating strings
- Stop nearly duplicated string
- Easier word-smithing
- Setup for translation services
- Abstract away date/time formatting

RequireJS
RequireJS has 'i18n' plugin
Auto-loads based on navigator.language
At the cost of user control

Testing
- test entire app in Englsih
- native speaker confirms translations
- wait on bug reports

Automate testing with Jasmine and Selenium

Server-side errors - return codes and not string

OSCON Server-Side Push: Comet, Web Sockets, and Server-Sent Events

The Server-Side Push: Comet, Web Sockets, and Server-Sent Events on the OSCON site.

Brian Sam-Bodden (Integrallis Software, LLC.)
2:30pm Wednesday, 07/24/2013

Polling - classic "are we there yet?" to allow the server to communicate updates. Self-DDoS attack

iFrame Streaming -
- embed an invisible iFrame (using jQuery)
- server returns chunks of data in a loop
- bind iFrame JS to parent page JS

XHR Streaming
- XMLHTTP request
- uses an AJAX call in background and sends JSON
- complexity now on client. need to watch the stream and determine the delta

Long polling
- most commonly used
- still used as a fallback
- blocks on server until something available then returns
- reestablish the request after server timeout
- thread of execution is blocked on the server

Flash streaming
- XML Socket
- creates a 1 pixel movie in page and uses a streaming movie's socket

Above are the less optimal

Push Frameworks

Comet
- previously associated with long polling
- now frameworks will interrogate the browser and pick the most appropriate technique
- provide both client and server side components
- many use a pub-sub protocol
- protocol is Bayeaux
faye.jcoglan.com
(faye is good for ruby)

Web Sockets
- Two way communications (tcp/ip socket)
- dedicated socket
- works with security, firewalls and proxies

Server-sent events
- from server to client
- unidirectional
- typically use UDP
- BOSH


WebRTC
-

Use a framework, allows graceful degradation