Task #3 - Header Module

In notebook:
FrontEndMasters Organising Javascript functionality
Created at:
2016-10-10
Updated:
2016-10-10
Tags:
JavaScript
We're going to start to reorganise the code we've written so far. 

Task is to convert each js file to a module and export it's functionality. 

He starts with header.js. In the original ​$modal​ becomes a global variable. We want to avoid this.
  //$(document).ready(function(){

  var $modal = $("[rel=js-modal]");
  
  $("[rel=js-header]").on("click","> [rel^=js]",function(evt){
  	evt.preventDefault();
  	evt.stopPropagation();
  	evt.stopImmediatePropagation();
  
  	var url = $(evt.target).attr("href");
  
  	$.ajax(url,{ dataType: "text" })
  	.then(function(contents){
  		$modal.html(contents).show();
  	});
  });

//});
He names his module ​Header​, then wraps the code with a function, that he runs immediately (IFEE).
He also extracts the click handler as ​clickHeaderLink​. Now, he also has to move up ​$modal​, so that it's a module-level variable. 

Finally he ​return​s ​init​ as his public API. 
  var Header = (function(){

	function clickHeaderLink(evt) {
		evt.preventDefault();
		..

		var url = $(evt.target).attr("href");

		$.ajax(url,{ .. })
		.then(..);
	}

	function init() {
		$modal = $("[rel=js-modal]");

		$("[rel=js-header]").on("click","> [rel^=js]",clickHeaderLink);
	}

	var $modal;

	return {
		init: init
	};

})();
He can put the ​onready​ handler elsewhere in the code. :
  $(document).ready(Header.init);
Now ​clickHeaderLink​ and ​$modal​ are private to the module and not exposed. 
The above code is equivalent to:
  function headerModule() {
  ..
  return {init:init};
}

var header = headerModule();