cajonでjavascriptを分割管理
JavaScript module loader for the browser that can load CommonJS/node and AMD modules
cajon(カホンって読むっぽい。ペルー発祥の打楽器の名前らしい)なんてものを見つけた。require.js上に構築されてるとかなんとか。require.jsもよく知らないんだけど、これはこれで簡単だしいいかも。
構成
.
├── index.html
└── js
├── cajon.js
├── controller.js
├── jquery.js
├── lib.js
├── model.js
├── template.js
└── view.js
index.html
<!DOCTYPE HTML> <html lang="ja"> <head> <meta charset="UTF-8"> <title>cajon test</title> <script src="js/cajon.js"></script> <script> require.config({ baseUrl: 'js' }); require(['jquery', 'lib'], function($, lib) { $.each(lib, function() { $('<li>').text(this.say()).appendTo('#hoge'); }); }); </script> </head> <body> <ul id="hoge"> </ul> </body> </html>
lib.js
module.exports = { template: require('./template'), model: require('./model'), controller: require('./controller'), view: require('./view') };
model.js
module.exports = { say: function() { return "I'm model.js" } };
view.js
module.exports = { say: function() { return "I'm view.js" } };
controller.js
module.exports = { say: function() { return "I'm controller.js" } };
template.js
module.exports = { say: function() { return "I'm template.js" } };
ブラウザでhtmlを開くと下のように表示される。
ちゃんとlib.js経由でmodel.js/view.js/controller.js/template.jsがそれぞれ読み込まれているのがわかる。