モジュール管理はモジュールローダーライブラリをRequireJSを利用
モジュールの定義方法
1 define(
2     module_id /*optional*/,
3     [dependencies] /*optional*/,
4     definition function /*関数 or オブジェクト*/
5 );
モジュールの利用方法
1 require(['foo', 'bar'], function ( foo, bar ) {
2     // rest of your code here
3     foo.doSomething();
4 });
RequireJSは使えば使うほどファイルが細分化され、しかも非同期読み込みができなくなっていくという問題を抱えている
解決方法
r.js -o path/to/app.config.js
プログラミングミスを発見したら
https://twitter.com/#!/dekokun/status/140428178211602434
sampleモジュール
1 define(function () {
2     var module = {};
3     // pos+2番目の文字列を取り出すメソッド
4     module.getCharacterAt = function (str, pos) {
5         return str.substr(pos+1, 1);// 0,1,2...
6     }
7     return module;
8 });
パスしていたsampleモジュールテストコード
1 define(["src/sample"], function (module) {
2     test("getCharacterAt", function () {
3         var str = "STRING";
4         equal(module.getCharacterAt(str, 0), "T");
5         equal(module.getCharacterAt("STRING", 2), "I");
6         equal(module.getCharacterAt(str, str.length - 2), "G");
7     });
8 });
この時は偶然にも想定した動作になっていた
1 define(["src/sample"], function (module) {
2     var char = module.getCharacterAt("STRING", "1");
3     console.log(char);// R
4 });
書き換えたモジュール
1 define(function () {
2     var module = {};
3     // pos + 2番目
4     module.getCharacterAt = function (str, pos) {
5         return str.charAt(pos + 1);
6     }
7     return module;
8 });
getCharacterAtの第ニ引数に文字列で値をしてみると…
1 module.getCharacterAt("STRING", "1");
2 // (an empty string) 空文字
文字列 + 数値 => 結合された文字列
1 "STRING".charAt(1);// T
2 "STRING".charAt("1"+1);// empty string
3 // "1"+1 => "11"
対策
など
テストモジュール
 1 define(["src/sample"], function (module) {
 2     test("getCharacterAt", function () {
 3         var str = "STRING";
 4         equal(module.getCharacterAt(str, 0), "T");
 5         equal(module.getCharacterAt("STRING", 2), "I");
 6         equal(module.getCharacterAt(str, str.length - 2), "G");
 7         // 第2引数が文字列の時は失敗 -> 第2引数は数値のみ受け入れる
 8         notEqual(module.getCharacterAt(str, "0"), "T");
 9     });
10 });
追加したテストに合わせた実装に変更する
 1 define(function () {
 2     var module = {};
 3     module.getCharacterAt = function (str, pos) {
 4         if (!(typeof pos === 'number' && isFinite(pos))) {
 5             return;// 第ニ引数が数値でないなら中止
 6         }
 7         return str.charAt(pos + 1);
 8     }
 9     return module;
10 });
| モジュール管理 | 1 | 
|---|---|
| AMD | 2 | 
| 問題点 | 3 | 
| r.jsでの結合 | 4 | 
| MVC? | 5 | 
| テスト | 6 | 
| e.g)レガシーなモジュール | 7 | 
| e.g)テストコード | 8 | 
| e.g)実際に呼び出すときにのコード | 9 | 
| e.g)リファクタリングしたモジュール | 10 | 
| e.g) 実際の実行結果は? | 11 | 
| e.g)原因 | 12 | 
| e.g)コードの修正 の前に テストの修正 | 13 | 
| e.g)テストを追加->コードを修正 | 14 | 
| まとめ | 15 | 
| Table of Contents | t | 
|---|---|
| Exposé | ESC | 
| Full screen slides | e | 
| Presenter View | p | 
| Source Files | s | 
| Slide Numbers | n | 
| Toggle screen blanking | b | 
| Show/hide slide context | c | 
| Notes | 2 | 
| Help | h |