Márton Salomváry
(Gawker Media)
budapest.js – JavaScript Meetup
12.03.2012
But no native support ☹
1 <script src="prototype.js"></script>
2 <script src="foo.js"></script>
3 <script src="bar.js"></script>
4 <script src="baz.js"></script>
But we learned:
1 var myApp = {
2 doThis: function() {...},
3 myModule: {
4 doThat: function() {...}
5 }
6 };
YAHOO.util.Dom.IEStyle.get()
1 var myModule = (function() {
2 var privateCounter = 0;
3 function privateFunc() {...};
4 return {
5 increment: function() {
6 privateCounter++;
7 },
8 getValue: function() {
9 return privateCounter;
10 }
11 };
12 })();
13
14 myModule.increment();
15 myModule.privateCounter; // won't work, it's private!
OK, we combine JavaScripts, organize code into modules, but...
Code complexity and size is growing - we need a tool to support this.
Create a module:
1 exports.doThis = function() {...};
2 exports.doThat = function() {...};
Use a module:
1 var myModule = require('myModule');
2 myModule.doThis();
Create a module:
1 define(['myLib'], function(myLib) {
2 return {
3 doThis: function() {...},
4 doThat: function() {...}
5 };
6 });
Use a module:
1 require(['myModule'], function(myModule) {
2 myModule.doThis();
3 });
Alternative implementation: curl.js.
1 define(['jquery', 'backbone', 'lib/mylib'],
2 function($, Backbone, myLib) {
3 // initialize the module, create private state, etc..
4 return {
5 doThis: function() {...},
6 doThat: function() {...}
7 };
8 });
As a dependency in another module:
1 define(['module1'], function(module1) {
2 module1.doThis();
3 module1.doThat();
4 });
Dynamically anywhere:
1 require(['module1'], function(module1) {
2 module1.doThis();
3 });
Look, we eliminated the tag soup!
1 <script src="/js/require.js" data-main="/js/main"></script>
This will load js/main.js and all the dependencies.
node r.js -o name=main out=main-built.js
1 require(['jquery',
2 'order!jquery/cookie',
3 'order!jquery/scrollto'],
4 function() {
5 $.cookie();
6 $('.foo').scrollTo();
7 });
It's 5.7K minified, gzipped ;)
Márton Salomváry
(Gawker Media)