Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // =========================
- // Utilities
- // =========================
- var utils = utils || {};
- // ========================================
- // Flag which defines the behaviour of the routes
- // and templates.
- // If set to 'true', the page will clean everytime
- // the route changes.
- //
- // ========================================
- utils.resetTemplateOnRouteChange = false;
- // ========================================
- // Que for all AJAX request for the current view,
- // cleaned after every reload.
- //
- // ========================================
- utils.queuedAjax = [];
- // ========================================
- // Load template file into the DOM webpage
- // Params:
- // url - url to the template file (starting from the index.html directory)
- // args - parameters to be put into the template, on the template mark
- // them with double curly braces like: {{argumentName}}
- // override - OPTIONAL override the previous template ( default: false )
- // callback - OPTIONAL callback function run after template is loaded
- //
- // ========================================
- utils.loadTemplate = (function(f,u,n,c){
- var $templateDom = $('#dynamic-template'),
- $ajaxCall;
- if( typeof n === 'function' && typeof c === 'undefined' ) c = n;
- $ajaxCall = $.get(f).success(function(response){
- var mustachedTemplate = Mustache.render(response,u);
- if( n === true ){
- $templateDom.html(mustachedTemplate);
- } else {
- $templateDom.append(mustachedTemplate);
- }
- if( typeof c === 'function' ){
- c(mustachedTemplate);
- }
- }).fail(function(response){
- console.warn('Template error',response);
- });
- utils.queuedAjax.push($ajaxCall);
- return true;
- });
- // ========================================
- // Load a json file from the back-end ( via GET )
- // Params:
- // url - url/path to the external, back-end server
- // callback - OPTIONAL callback function for the request
- //
- // ========================================
- utils.getData = utils.loadJSON = (function(f,u){
- var $ajaxCall,
- json;
- $ajaxCall = $.get(f).success(function(response){
- if( typeof response === 'String'){
- try {
- json = JSON.parse(response);
- } catch(exception){
- console.warn('JSON error',exception);
- }
- } else {
- json = response;
- }
- if( typeof u === 'function' ){
- u( json || null );
- }
- }).fail(function(response){
- // console.warn('JSON error',response);
- });
- utils.queuedAjax.push($ajaxCall);
- });
- // ========================================
- // Send data to the back-end ( via POST )
- // Params:
- // url - url/path to the external, back-end server
- // data - parameters sent to the back-end
- // callback - OPTIONAL function called after the back-end responds
- //
- // ========================================
- utils.sendData = utils.sendJSON = (function(f,u,n){
- var $ajaxCall;
- $ajaxCall = $.post(f,u).success(function(response){
- if( typeof response === 'String'){
- try {
- json = JSON.parse(response);
- } catch(exception){
- console.warn('JSON error',exception);
- }
- } else {
- json = response;
- }
- if( typeof n === 'function' ){
- n( json || null );
- }
- }).fail(function(response){
- console.warn('POST error',response);
- });
- });
- // ========================================
- // Call a callback when a proper URL is given
- // Params:
- // url - url/path expected
- // callback - function called after URL is matched with the expected
- //
- // ========================================
- utils.onRoute = (function(f,u){
- var urlParams = [];
- if( f === null ){
- f = 'index';
- }
- if( f[0] === '#' ){
- f = f.substr(1);
- }
- urlParams = (f.match(/\{\w+\}/g) || []).map(function(paramQuote){
- return paramQuote.substr(1,paramQuote.length-2);
- });
- f = f.replace(/\{\w+\}/g,'{p}');
- if( typeof u === 'function' ){
- utils.routesMapping[f] = {
- callback: u,
- params: urlParams
- };
- }
- return utils;
- });
- // ========================================
- // Routing Setup Function
- // ========================================
- utils.routesMapping = {};
- $(function(){
- $(window).on('hashchange load',function(ev){
- var route = window.location.href.substr(window.location.origin.length).substr(2),
- routeCallbackParams = {},
- routeCallback;
- utils.clearAjaxRequests();
- if( utils.resetTemplateOnRouteChange === true ){
- utils.clearTemplates();
- }
- for( var path in utils.routesMapping ){
- var pathOption = utils.routesMapping[path],
- regexMapping,
- regexMatch,
- regexSplit,
- splitStep;
- if( pathOption.params.length < Object.keys(routeCallbackParams).length && Object.keys(routeCallbackParams).length !== 0 ){
- continue;
- }
- var a;
- regexMapping = path.replace(/\//g,'\\/').replace(/{p}/g,'\\w+');
- if( (regexMatch = route.match(new RegExp(regexMapping,'g')) || []) && regexMatch.length === 1 ){
- routeCallbackParams = {};
- regexSplit = (path.split(/\{\w+\}/) || []).filter(function(value){
- return value;
- });
- splitStep = route;
- for( var i = 0, j = regexSplit.length; i < j; i++ ){
- var splitIndex = splitStep.indexOf(regexSplit[i]),
- splitHead = splitStep.slice(0, splitIndex),
- splitTail = splitStep.slice(splitIndex + regexSplit[i].length);
- splitStep = splitTail;
- if( splitHead && splitHead.indexOf('/') === -1 ){
- routeCallbackParams[pathOption.params[i-1]] = splitHead;
- }
- if( splitTail && i === j-1 && splitTail.indexOf('/') === -1 ){
- routeCallbackParams[pathOption.params[i]] = splitTail;
- }
- }
- routeCallback = pathOption.callback;
- a = pathOption;
- }
- }
- if( !routeCallback ){
- routeCallback = utils.routesMapping['index'];
- a = 'index';
- }
- console.log(a);
- if( typeof routeCallback === 'function' ){
- routeCallback(routeCallbackParams);
- }
- });
- });
- // ========================================
- // Remove previous templates
- // ========================================
- utils.clearTemplates = (function(){
- var $templateDom = $('#dynamic-template');
- $templateDom.html('');
- });
- // ========================================
- // Cancel previous AJAX requests
- // ========================================
- utils.clearAjaxRequests = (function(){
- $.each(utils.queuedAjax, function(i,request){
- request.abort();
- });
- utils.queuedAjax = [];
- });
- // TODO: (URL masking function) window.history.pushState(null, null, route.substr(1) );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement