Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ///<reference path="~/Scripts/jquery-1.5.1-vsdoc.js" />
- /*
- Single Page Application scripts
- $.spa(); // calls the init method with default options
- $.spa({ // calls the init method with custom options
- cache:true,
- linkSelector : "a.mylink",
- loadIntoSelector: "#mycontent",
- beforeload: function(element,url) {
- $("#mystatus").show();
- },
- error: function (element, url, status,errorThrown, xhr) {
- element.html("Opps, an error: " + errorThrown);
- },
- afterload: function(element,url,response, status, xhr) {
- $("#mystatus").hide();
- }
- });
- */
- (function ($) {
- var settings = {
- initialUrl: null, /* The url that get's called when page loads for the first time*/
- cache: false, /* If true, the html is cached for all requests*/
- ajaxCache: true, /* Sets jquery's ajax cache setting, default is 'false'*/
- ajaxType: "GET", /* Sets jquery's ajax method type setting,default is 'GET'*/
- debug: false, /* If true, debug statements are written to the console*/
- enabled: true, /* If false, spa will not request anything*/
- loadIntoSelector: "#content", /* The element id or jquery selector statement that the request contents will be loaded into*/
- linkSelector: ".app-link", /* The element id or jquery selector statement that spa will subscribe to it's 'click' event to perform the request*/
- beforeload: function (element, url) { return true; }, /* Fired before each request, return false to stop the request*/
- afterload: function (element, url, response, status, xhr) { }, /* Fired after each request*/
- error: function (element, url, status, errorThrown, xhr) { }, /* Fired after when an the request returns an error*/
- settitle: function (element, url, title) { /* Fired after each request, return a string value to set the document's title*/
- return title;
- }
- };
- /*Debug utility*/
- function debug(msg) {
- if (!settings.debug) return;
- if (window._debug) {
- _debug(msg);
- }
- else {
- if (window.console)
- if (window.console.debug)
- window.console.debug(msg);
- }
- };
- var impl = {};
- impl = {
- cache: new spaHash(),
- /*Return's the url with a query string that will return a fresh request*/
- cacheifyurl: function (url) {
- if (url.indexOf("?") === -1) {
- url += "?";
- } else {
- url += "&";
- }
- url += "t=_" + new Date().getTime();
- return url;
- },
- /*The object list of url's not to load, used for custom requests*/
- noloads: new spaHash(),
- /*A hash of url/button elements to track and modifiy the ui for each request, basically to change the button states*/
- buttons: new spaHash(),
- urlcache: new spaHash(),
- notcached: new spaHash(),
- currentreq: new spaHash(),
- };
- impl.methods = {
- /*Initialization method,fires when the page loads up*/
- init: function (options) {
- if (options) {
- $.extend(settings, options);
- }
- debug("spa->init(): settings -> " + JSON.stringify(settings));
- var buttonLinkSelector = settings.linkSelector || "a.app-link";
- $(buttonLinkSelector).each(function () {
- var ele = $(this);
- var url = ele.attr('data-href');
- impl.methods.addUIButton(url, ele);
- });
- /*find and add the urls to 'urlcache' list that have an attribute of 'cachereq = 1' */
- $("*[cachereq='1']").each(function () {
- var ele = $(this);
- var url = ele.attr('data-href');
- impl.urlcache.setItem(url, ele);
- debug("button cache : " + ele.attr('id'));
- });
- /*find and add the urls to 'notcached' list that have an attribute of 'cachereq = 0' */
- $("*[cachereq='0']").each(function () {
- var ele = $(this);
- var url = ele.attr('data-href');
- impl.notcached.setItem(url, ele);
- debug("ignore cache : " + ele.attr('id'));
- });
- /*subscribe to each link/button 'click' event*/
- $(buttonLinkSelector).live('click', function (e) {
- var url = $(this).attr('data-href');
- var datacache = $(this).attr('data-cache');
- var cachereq = $(this).attr('cachereq');
- debug("spa-> click() " + url);
- impl.methods.load(url,null,cachereq);
- e.preventDefault();
- });
- /*attach to the $.history initilize callback*/
- $.history.init(function (url) {
- impl.methods.loadElement(url);
- });
- },
- /*Loads a url and tracks the history*/
- load: function (url, onload,cachereq) {
- if (!settings.enabled)
- return;
- if(cachereq === null){
- cachereq = cachereq || settings.cache;
- }
- debug("load()-> cachereq: " + cachereq);
- if (onload) {
- if (impl.noloads.hasItem(url)) {
- onload(url, settings);
- debug("spa->load() hasItem [true] -> " + url);
- return;
- }
- impl.noloads.setItem(url, onload);
- debug("spa->load() noloads " + url);
- }
- else {
- var notcached = impl.notcached.getItem(url);
- if (notcached != null) {
- debug("spa->load() NOT CACHED url: " + url);
- impl.methods.loadElement(url,cachereq);
- return;
- }
- else {
- debug("SPA->load()->impl.methods.loadElement(url) url:" + url);
- impl.methods.loadElement(url,cachereq);
- }
- }
- $.history.load(url);
- // debug("spa->load() url: " + url);
- },
- /*Called from the $.history module to when history is moved back or forward*/
- loadElement: function (url,cachereq) {
- cachereq = cachereq || false;
- debug("loadElement() url -> " + url);
- if (impl.noloads.hasItem(url)) {
- var onload = impl.noloads.getItem(url);
- if (onload) {
- onload(url, settings);
- debug("loadElement() onload called -> " + url);
- return false;
- }
- }
- var inithistory = settings.initialUrl;
- if (url == null || url == "") {
- url = inithistory;
- debug("settings.initialUrl -> " + settings.initialUrl);
- }
- if (url == undefined || url == null || url == "")
- return false;
- var loadIntoSel = settings.loadIntoSelector || "#content";
- var loadInto = $(loadIntoSel);
- if (settings.beforeload) {
- if (settings.beforeload(loadInto, url) === false) {
- return false;
- }
- }
- impl.methods.loadUIState(url);
- /*get global cache settings*/
- var cacheRequest = cachereq;
- var loadUrl = url;
- var notcached = impl.notcached.getItem(url);
- if (notcached != null) {
- cacheRequest = false;
- debug("NOT CACHED: " + url + " id: " + notcached);
- } else {
- var cachedLink = impl.urlcache.getItem(url);
- if (cachedLink != null) {
- cacheRequest = true;
- debug("CACHED URL :" + url + " id: " + cachedLink);
- }
- }
- if (cacheRequest === true) { /*modifies the url that will cache request*/
- debug("CACHING -> " + url);
- var cachedhtml = impl.cache.getItem(url);
- if (cachedhtml) {
- debug("CACHE HIT -> " + url);
- loadInto.html(cachedhtml);
- /*calls the afterload() method*/
- if (settings.afterload) {
- settings.afterload($(loadInto), url, cachedhtml, null, null);
- }
- return;
- }
- }
- var ajaxtype = settings.ajaxType || "GET";
- var timestamp = new Date().getTime();
- var running = impl.currentreq.getItem(url) || false;
- if(running){
- impl.currentreq.setItem(url,false);
- return;
- }
- impl.currentreq.setItem(url,true);
- debug("$.ajax " + ajaxtype + " ts: " + timestamp + " -> " + loadUrl);
- /*Calls $.ajax method*/
- $.ajax({
- url: loadUrl,
- type: settings.ajaxType || "GET",
- cache: settings.ajaxCache || false,
- success: function (data, status, xhr) {
- try {
- impl.currentreq.setItem(url,false);
- debug("ts: " + timestamp);
- /*load's html into 'loadInto' element*/
- loadInto.html(data);
- if (cacheRequest === true) {
- impl.cache.setItem(url, data);
- }
- /*looks for the title in the response and sets the document.title*/
- var spa_title = loadInto.find("#spa_title");
- var title = "";
- if (spa_title) {
- title = spa_title.html();
- }
- if (settings.settitle) {
- document.title = settings.settitle(loadInto, url, title);
- } else {
- document.title = title;
- }
- } catch (e) {
- throw e;
- }
- finally {
- /*calls the afterload() method*/
- if (settings.afterload) {
- settings.afterload($(loadInto), url, data, status, xhr);
- }
- }
- },
- error: function (xhr, status, errorThrown) {
- loadInto.empty();
- try {
- var msg = "Sorry but there was an error: ";
- debug(msg + " " + errorThrown);
- if (settings.error) {
- settings.error(loadInto, url, status, errorThrown, xhr);
- }
- } catch (e) {
- throw e;
- }
- finally {
- /*calls the afterload() method*/
- if (settings.afterload) {
- settings.afterload(loadInto, url, null, status, xhr);
- }
- }
- }
- });
- },
- /*Add ui button with it's associated url to change it's state when the history is moved*/
- addUIButton: function (url, button) {
- if (!button) return false;
- impl.buttons.setItem(url, button);
- debug("addUIButton -> id:" + button.attr("id"));
- return true;
- },
- /*Changes the button states when a url is loaded*/
- loadUIState: function (url) {
- /*set all buttons to thier default state*/
- var buttonKeys = impl.buttons.getKeys();
- var selbutton = impl.buttons.getItem(url);
- if (!selbutton) {
- return;
- }
- $(".spa-button").each(function () {
- var btn = $(this);
- btn.addClass("ui-state-default");
- btn.removeClass("ui-state-focus");
- btn.removeClass("ui-state-active");
- btn.removeClass("ui-state-hover");
- /*debug("Setting class : " + $(btn).attr("id"));*/
- });
- /*set the button associated with the url to the 'hover state*/
- if (selbutton) {
- selbutton.addClass("ui-state-focus");
- }
- }
- };
- $.fn.spa = function (method) {
- if (impl.methods[method]) {
- return impl.methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
- } else if (typeof method === 'object' || !method) {
- return impl.methods.init.apply(this, arguments);
- } else {
- $.error('Method ' + method + ' does not exist on jQuery.spa');
- }
- };
- var self = $.extend($.fn.spa, impl.methods);
- $.spa = self;
- })(jQuery);
- /*A hash table*/
- function spaHash() {
- this.length = 0;
- this.items = new Array();
- for (var i = 0; i < arguments.length; i += 2) {
- if (typeof (arguments[i + 1]) != 'undefined') {
- this.items[arguments[i]] = arguments[i + 1];
- this.length++;
- }
- }
- this.removeItem = function (in_key) {
- var tmp_previous;
- if (typeof (this.items[in_key]) != 'undefined') {
- this.length--;
- var tmp_previous = this.items[in_key];
- delete this.items[in_key];
- }
- return tmp_previous;
- }
- this.getItem = function (in_key) {
- return this.items[in_key];
- }
- this.setItem = function (in_key, in_value) {
- var tmp_previous;
- if (typeof (in_value) != 'undefined') {
- if (typeof (this.items[in_key]) == 'undefined') {
- this.length++;
- } else {
- tmp_previous = this.items[in_key];
- }
- this.items[in_key] = in_value;
- }
- return tmp_previous;
- }
- this.getKeys = function () {
- var tmp_keys = [];
- for (var key in this.items) {
- tmp_keys.push(key);
- }
- return tmp_keys;
- }
- this.hasItem = function (in_key) {
- return typeof (this.items[in_key]) != 'undefined';
- }
- this.clear = function () {
- for (var i in this.items) {
- delete this.items[i];
- }
- this.length = 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment