Calling the API

In notebook:
FrontEndMasters Organising Javascript functionality
Created at:
2016-10-12
Updated:
2016-10-12
Tags:
JavaScript jQuery libraries
Opens about.grips.html. 
  {$define "#content" }

<div id="content">

	<h1>About</h1>
	<p>
	  <!--  ++++ ↴  -->
	  <input type="checkbox" rel="js-local" id="local" checked> <label for="local">Local</label><br>
	  <input type="button" value="gimme" rel="js-gimme" />
	</p>
	<p>
		{$partial "#answer" $}
	</p>

</div>

{$}
His system is set up that it will automatically try to load a file with same name as the page (about.js) 
Duplicates index.js as about.js.

Uses some conventions e.g. passing ​window​ as ​context​. 
He adds the loading in load.js to load the Foo.js. 
  (function(context){

// 2. gimme
	function gimme(evt){
		var $local = $("[rel='js-local']");
    
    if($local.is(":checked")) {
      alert(Foo.random());      
    } else {
      // 3. API call to the server
      // jQuery will automatically parse JSON
      $.ajax("/Foo").then(function(resp){
        alert("Remote: " + resp.answer);
      });
    }
		
	}

// 1. add click handler
	function init(){
		$("[rel='js-gimme']").click(gimme);
	}

	function teardown(){}

	Pages.page_scripts["/about"] = {
		init: init,
		teardown: teardown
	};

})(window);

Needs to restart the server. 
When local checkbox on the page is  unchecked, making an AJAX call, he sees on the Network tab of the dev tools the request being made. 

A great use case for this pattern (sharing modules between server and browser), would be a form submit action. It can either do it by AJAX or by a full page request.