diff js/tutorial.js @ 95:86158b61b732 blog-post

Reworked the tutorial so that we don't have to have each snippet be a callback from the previous snippet, which makes the tutorial a lot harder to follow.
author Atul Varma <varmaa@toolness.com>
date Tue, 21 Apr 2009 12:13:18 -0700
parents 17ce8b6be452
children
line wrap: on
line diff
--- a/js/tutorial.js	Tue Apr 21 10:11:12 2009 -0700
+++ b/js/tutorial.js	Tue Apr 21 12:13:18 2009 -0700
@@ -32,24 +32,45 @@
       $('#try-my-view').text('');
       var code = $('.try-code').val();
       eval(code);
-      eval('tryMyView();');
     }
 
     $('.try-code').blur(executeTryCode);
     $('#content').fadeIn();
 
-    // Iterate through all the code snippets and trim them.
-    var allCode = '';
+    // Iterate through all the code snippets, gather them for
+    // execution, and trim them for display.
+    var snippets = [];
+    var DONE_FUNC_NAME = 'DONE';
+    var DONE_FUNC_CALL = 'DONE();';
     $('.example-code').each(
       function() {
         var code = $(this).val() || $(this).text();
-        allCode += code;
-        $(this).text(jQuery.trim(code));
+        if (code.indexOf(DONE_FUNC_CALL) == -1)
+          code += DONE_FUNC_CALL;
+        var snippet = {code: code};
+        snippets.push(snippet);
+        code = code.replace(DONE_FUNC_CALL, '');
+        code = jQuery.trim(code);
+        if ($(this).val())
+          $(this).val(code);
+        else
+          $(this).text(code);
       });
 
+    snippets.reverse();
+
     // Now execute all the code snippets.
-    var dataUri = 'data:text/javascript,' + encodeURI(allCode);
-    var script = document.createElement('script');
-    script.setAttribute('src', dataUri);
-    document.body.appendChild(script);
+    function executeNextSnippet() {
+      if (snippets.length) {
+        var snippet = snippets.pop();
+        var dataUri = 'data:text/javascript,' + encodeURI(snippet.code);
+        var script = document.createElement('script');
+        script.setAttribute('src', dataUri);
+        document.body.appendChild(script);
+      }
+    }
+
+    window[DONE_FUNC_NAME] = executeNextSnippet;
+
+    executeNextSnippet();
   });