Commit da7cc548 authored by Thomas Lechauve's avatar Thomas Lechauve

Manually linted (clean) javascript files

parent f4fad40f
$(document).bind("mobileinit", function () { $(document).bind('mobileinit', function () {
var spinOptions = {color: "#FFFFFF", lines:30, length:0, width:5, radius:7, rotate:0, trail:60, speed:1.6}; 'use strict';
var spinOptions = {color: '#FFFFFF', lines: 30, length: 0, width: 5, radius: 7, rotate: 0, trail: 60, speed: 1.6};
$.vifib = {} || $.vifib; if (!$.vifib) {
$.vifib = {};
}
//SlapOs configuration //SlapOs configuration
$(document).slapos({ $(document).slapos({
...@@ -12,12 +15,12 @@ $(document).bind("mobileinit", function () { ...@@ -12,12 +15,12 @@ $(document).bind("mobileinit", function () {
// Google application id // Google application id
'ggappid': '380290002359.apps.googleusercontent.com' 'ggappid': '380290002359.apps.googleusercontent.com'
}); });
// show loading during ajax request // show loading during ajax request
$(document).ajaxStart(function () { $(document).ajaxStart(function () {
$("#loading").spin(spinOptions); $('#loading').spin(spinOptions);
}).ajaxStop(function () { }).ajaxStop(function () {
$("#loading").spin(false); $('#loading').spin(false);
}); });
//$(document).slapos('store', 'host', '/fake'); //$(document).slapos('store', 'host', '/fake');
......
...@@ -65,7 +65,7 @@ ...@@ -65,7 +65,7 @@
}, },
request: function (type, method, args) { request: function (type, method, args) {
var statusCode, data; var statusCode, data, ajaxOptions;
if (args.hasOwnProperty('statusCode')) { if (args.hasOwnProperty('statusCode')) {
statusCode = args.statusCode || methods.statusDefault(); statusCode = args.statusCode || methods.statusDefault();
} else { } else {
...@@ -78,24 +78,24 @@ ...@@ -78,24 +78,24 @@
} }
delete args.data; delete args.data;
$.extend(args, {statusCode: statusCode}); $.extend(args, {statusCode: statusCode});
var ajaxOptions = { ajaxOptions = {
type: type, type: type,
url: $(this).slapos('host') + method, url: $(this).slapos('host') + method,
contentType: 'application/json', contentType: 'application/json',
data: JSON.stringify(data), data: JSON.stringify(data),
datatype: 'json', datatype: 'json',
context: $(this), context: $(this),
headers: { headers: {
'Accept': 'application/json', 'Accept': 'application/json',
}, },
beforeSend: function (xhr) { beforeSend: function (xhr) {
if ($(this).slapos('access_token')) { if ($(this).slapos('access_token')) {
xhr.setRequestHeader('Authorization', $(this).slapos('store', 'token_type') + ' ' + $(this).slapos('access_token')); xhr.setRequestHeader('Authorization', $(this).slapos('store', 'token_type') + ' ' + $(this).slapos('access_token'));
} }
} }
}; };
$.extend(ajaxOptions, args); $.extend(ajaxOptions, args);
return $.ajax(ajaxOptions); return $.ajax(ajaxOptions);
}, },
instanceList: function (args) { instanceList: function (args) {
...@@ -110,7 +110,7 @@ ...@@ -110,7 +110,7 @@
instanceRequest: function (args) { instanceRequest: function (args) {
return $(this).slapos('request', 'POST', '/instance', args); return $(this).slapos('request', 'POST', '/instance', args);
}, },
instanceBang: function (url, args) { instanceBang: function (url, args) {
$.extend(args, {url: url + '/bang'}); $.extend(args, {url: url + '/bang'});
return $(this).slapos('request', 'POST', '', args); return $(this).slapos('request', 'POST', '', args);
...@@ -129,7 +129,7 @@ ...@@ -129,7 +129,7 @@
$.extend(args, {url: url}); $.extend(args, {url: url});
return $(this).slapos('request', 'GET', '', args); return $(this).slapos('request', 'GET', '', args);
}, },
computerList: function (args) { computerList: function (args) {
return $(this).slapos('request', '', args); return $(this).slapos('request', '', args);
}, },
...@@ -138,16 +138,17 @@ ...@@ -138,16 +138,17 @@
$.extend(args, {url: url}); $.extend(args, {url: url});
return $(this).slapos('request', 'GET', '', args); return $(this).slapos('request', 'GET', '', args);
} }
}; };
$.fn.slapos = function (method) { $.fn.slapos = function (method) {
var r;
if (methods[method]) { if (methods[method]) {
return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); r = methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
} else if (typeof method === 'object' || !method) { } else if (typeof method === 'object' || !method) {
return methods.init.apply(this, arguments); r = methods.init.apply(this, arguments);
} else { } else {
$.error('Method ' + method + ' does not exist on jQuery.slapos'); $.error('Method ' + method + ' does not exist on jQuery.slapos');
} }
return r;
}; };
}(jQuery)); }(jQuery));
'use strict'; (function (window, $) {
var getDevice = function (w) { 'use strict';
if (w < 500) { var getDevice = function (w) {
return 'mobile'; if (w < 500) {
} return 'mobile';
if (w < 900) { }
return 'tablet'; if (w < 900) {
} return 'tablet';
return 'desktop'; }
}, return 'desktop';
device = getDevice($(window).width());
var body = $("body");
$.vifib.devices = {
"mobile": function (url) {
$('body')
.route('add', '')
.done($.vifib.mobile.overview);
$('body')
.route('add', '/login/facebook')
.done($.vifib.login.facebook);
$('body')
.route('add', '/login/google')
.done($.vifib.login.google);
// when Google send back the token, it reset hashtag from url
$('body')
.route('add', 'access_token=<path:path>')
.done($.vifib.login.googleRedirect);
$('body')
.route('add', '/overview')
.done($.vifib.mobile.overview);
$('body')
.route('add', '/library<path:url>')
.done($.vifib.mobile.library.dispatch);
$('body')
.route('add', '/dashboard<path:url>')
.done($.vifib.mobile.dashboard.dispatch);
},
"tablet": function () {
$('body')
.route('add', '')
.done($.vifib.tablet.overview);
$('body')
.route('add', '/login/facebook')
.done($.vifib.login.facebook);
$('body')
.route('add', '/login/google')
.done($.vifib.login.google);
// when Google send back the token, it reset hashtag from url
$('body')
.route('add', 'access_token=<path:path>')
.done($.vifib.login.googleRedirect);
$('body')
.route('add', '/overview')
.done($.vifib.tablet.overview);
$('body')
.route('add', '/library<path:url>')
.done($.vifib.tablet.library.dispatch);
$('body')
.route('add', '/dashboard<path:url>')
.done($.vifib.tablet.dashboard.dispatch);
}, },
"desktop": function () { body = $("body");
$('body')
.route('add', '')
.done($.vifib.desktop.redirect);
$('body')
.route('add', '<path:url>')
.done($.vifib.desktop.dispatch);
}
}
$.vifib.isauthenticated = function () { $.vifib.device = getDevice($(window).width());
var token_type = $(document).slapos('store', 'token_type'); $.vifib.devices = {
if ($(document).slapos('access_token') === undefined || token_type === undefined) { "mobile": function (url) {
return false; $('body')
} .route('add', '')
if (token_type === 'Google') { .done($.vifib.mobile.overview);
$('body')
} else if (token_type === 'Facebook') { .route('add', '/login/facebook')
.done($.vifib.login.facebook);
} $('body')
return false; .route('add', '/login/google')
} .done($.vifib.login.google);
// when Google send back the token, it reset hashtag from url
$('body')
.route('add', 'access_token=<path:path>')
.done($.vifib.login.googleRedirect);
$('body')
.route('add', '/overview')
.done($.vifib.mobile.overview);
$('body')
.route('add', '/library<path:url>')
.done($.vifib.mobile.library.dispatch);
$('body')
.route('add', '/dashboard<path:url>')
.done($.vifib.mobile.dashboard.dispatch);
},
"tablet": function () {
$('body')
.route('add', '')
.done($.vifib.tablet.overview);
$('body')
.route('add', '/login/facebook')
.done($.vifib.login.facebook);
$('body')
.route('add', '/login/google')
.done($.vifib.login.google);
// when Google send back the token, it reset hashtag from url
$('body')
.route('add', 'access_token=<path:path>')
.done($.vifib.login.googleRedirect);
$('body')
.route('add', '/overview')
.done($.vifib.tablet.overview);
$('body')
.route('add', '/library<path:url>')
.done($.vifib.tablet.library.dispatch);
$('body')
.route('add', '/dashboard<path:url>')
.done($.vifib.tablet.dashboard.dispatch);
},
"desktop": function () {
$('body')
.route('add', '')
.done($.vifib.desktop.redirect);
$('body')
.route('add', '<path:url>')
.done($.vifib.desktop.dispatch);
}
};
$.vifib.startrouter = function () { $.vifib.startrouter = function () {
$('body') $('body')
.route('go', $.url.getPath()) .route('go', $.url.getPath())
.fail($.vifib.mobile.nopage); .fail($.vifib.mobile.nopage);
} };
/* Thanks to Ben Alman /* Thanks to Ben Alman
* https://raw.github.com/cowboy/jquery-misc/master/jquery.ba-serializeobject.js * https://raw.github.com/cowboy/jquery-misc/master/jquery.ba-serializeobject.js
*/ */
$.fn.serializeObject = function(){ $.fn.serializeObject = function () {
var obj = {}; var obj = {};
$.each( this.serializeArray(), function(i,o){ $.each(this.serializeArray(), function (i, o) {
var n = o.name, var n = o.name,
v = o.value; v = o.value;
obj[n] = obj[n] === undefined ? v obj[n] = obj[n] === undefined ? v
: $.isArray( obj[n] ) ? obj[n].concat( v ) : $.isArray(obj[n]) ? obj[n].concat(v)
: [ obj[n], v ]; : [obj[n], v];
}); });
return obj; return obj;
} };
$.fn.spin = function(opts) {
this.each(function() {
var $this = $(this),
data = $this.data();
if (data.spinner) {
data.spinner.stop();
delete data.spinner;
}
if (opts !== false) {
data.spinner = new Spinner($.extend({color: $this.css('color')}, opts)).spin(this);
}
});
return this;
}
$(document).ready(function () { $.fn.spin = function (opts) {
// bind on resize screen event this.each(function () {
$(window).resize(function () { var $this = $(this),
setTimeout(function () { data = $this.data();
var curdevice = getDevice($(window).width()); if (data.spinner) {
if (device !== curdevice) { data.spinner.stop();
device = curdevice; delete data.spinner;
$.routereset();
$.vifib.devices[device]();
$.vifib.startrouter();
} }
}, 800); if (opts !== false) {
}); data.spinner = new Spinner($.extend({color: $this.css('color')}, opts)).spin(this);
}
});
return this;
};
// Url change event $(document).ready(function () {
$.url.onhashchange(function () { // bind on resize screen event
var options = $.url.getOptions(); $(window).resize(function () {
if (options.hasOwnProperty('access_token')) { setTimeout(function () {
$(document).slapos('access_token', options.access_token); var curdevice = getDevice($(window).width());
} if ($.vifib.device !== curdevice) {
$.vifib.devices[device](); $.vifib.device = curdevice;
$.vifib.startrouter(); $.routereset();
$.vifib.devices[$.vifib.device]();
$.vifib.startrouter();
}
}, 800);
});
// Url change event
$.url.onhashchange(function () {
var options = $.url.getOptions();
if (options.hasOwnProperty('access_token')) {
$(document).slapos('access_token', options.access_token);
}
$.vifib.devices[$.vifib.device]();
$.vifib.startrouter();
});
}); });
}); }(window, jQuery));
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
$.vifib.onepanel = function (panel, data) { (function (window, $) {
var page = $('<div data-role="page"></div>') 'use strict';
content = $('<div data-role="content"></div>') $.vifib.onepanel = function (panel, data) {
.append(Mustache.render(panel, data)); var page = $('<div data-role="page"></div>'),
page.append(content); content = $('<div data-role="content"></div>')
return $(page); .append(Mustache.render(panel, data));
} page.append(content);
return $(page);
};
$.vifib.twopanel = function (panels, data) { $.vifib.twopanel = function (panels, data) {
var page = $('<div data-role="page"></div>') var page = $('<div data-role="page"></div>')
.append($.vifib.makecontent(panels, data)); .append($.vifib.makecontent(panels, data));
return $(page); return $(page);
} };
$.vifib.threepanel = function (panels, data) { $.vifib.threepanel = function (panels, data) {
var page = $('<div data-role="page"></div>') var page = $('<div data-role="page"></div>')
.append($.vifib.makecontent(panels, data)); .append($.vifib.makecontent(panels, data));
return $(page); return $(page);
} };
$.vifib.replacepanel = function (context, panel, data) { $.vifib.replacepanel = function (context, panel, data) {
context.html(Mustache.render(panel, data)); context.html(Mustache.render(panel, data));
$(':jqmData(role=page)').trigger('pagecreate'); $(':jqmData(role=page)').trigger('pagecreate');
} };
$.vifib.makecontent = function (panels, data) { $.vifib.makecontent = function (panels, data) {
var i = 0, var i = 0,
pandata, pandata,
gridname = { gridname = {
2: 'ui-grid-a', 2: 'ui-grid-a',
3: 'ui-grid-b', 3: 'ui-grid-b',
4: 'ui-grid-c', 4: 'ui-grid-c',
5: 'ui-grid-d', 5: 'ui-grid-d'
}, },
divcontent = $('<div data-role="content" class="' + gridname[panels.length] + '"></div>'); divcontent = $('<div data-role="content" class="' + gridname[panels.length] + '"></div>');
for (i; i < panels.length; i ++) { for (i; i < panels.length; i += 1) {
pandata = data === undefined ? undefined : data[i]; pandata = data === undefined ? undefined : data[i];
divcontent.append($.vifib.makepanel(panels[i], pandata, i)); divcontent.append($.vifib.makepanel(panels[i], pandata, i));
} }
return divcontent; return divcontent;
} };
$.vifib.makepanel = function (panel, data, index) { $.vifib.makepanel = function (panel, data, index) {
var blockname = [ var blockname = [
'ui-block-a', 'ui-block-a',
'ui-block-b', 'ui-block-b',
'ui-block-c', 'ui-block-c',
'ui-block-d', 'ui-block-d',
'ui-block-e', 'ui-block-e'
], ],
divpane = $('<div class="' + blockname[index] + '">') divpane = $('<div class="' + blockname[index] + '">')
.append('<section id="panel-' + index + '">' + Mustache.render(panel, data) + '</section>'); .append('<section id="panel-' + index + '">' + Mustache.render(panel, data) + '</section>');
return divpane; return divpane;
} };
$.vifib.changepage = function (page) { $.vifib.changepage = function (page) {
$('[id^=panel]').remove(); $('[id^=panel]').remove();
$('#slider').remove(); $('#slider').remove();
$('#loading').remove(); $('#loading').remove();
$('body').append($(page)); $('body').append($(page));
$.mobile.changePage($(page), { $.mobile.changePage($(page), {
changeHash: false, changeHash: false,
transition: $.mobile.defaultPageTransition transition: $.mobile.defaultPageTransition
}); });
} };
}(window, jQuery));
/*global window, jQuery */
/*!
* route.js v1.0.0
*
* Copyright 2012, Romain Courteaud
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Date: Mon Jul 16 2012
*/
"use strict";
(function (window, $) {
$.extend({
StatelessDeferred: function () {
var doneList = $.Callbacks("memory"),
promise = {
done: doneList.add,
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function (obj) {
var i,
keys = ['done', 'promise'];
if (obj === undefined) {
obj = promise;
} else {
for (i = 0; i < keys.length; i += 1) {
obj[keys[i]] = promise[keys[i]];
}
}
return obj;
}
},
deferred = promise.promise({});
deferred.resolveWith = doneList.fireWith;
// All done!
return deferred;
}
});
var routes = [],
current_priority = 0,
methods = {
add: function (pattern, priority) {
var i = 0,
inserted = false,
length = routes.length,
dfr = $.StatelessDeferred(),
context = $(this),
escapepattern,
matchingpattern;
if (priority === undefined) {
priority = 0;
}
if (pattern !== undefined) {
// http://simonwillison.net/2006/Jan/20/escape/
escapepattern = pattern.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&");
matchingpattern = escapepattern
.replace(/<int:\w+>/g, "(\\d+)")
.replace(/<path:\w+>/g, "(.+)")
.replace(/<\w+>/g, "([^/]+)");
while (!inserted) {
if ((i === length) || (priority >= routes[i][2])) {
routes.splice(i, 0, [new RegExp('^' + matchingpattern + '$'), dfr, priority, context]);
inserted = true;
} else {
i += 1;
}
}
}
return dfr.promise();
},
go: function (path, min_priority) {
var dfr = $.Deferred(),
context = $(this),
result;
if (min_priority === undefined) {
min_priority = 0;
}
setTimeout(function () {
var i = 0,
found = false,
slice_index = -1,
slice_priority = -1;
for (i = 0; i < routes.length; i += 1) {
if (slice_priority !== routes[i][2]) {
slice_priority = routes[i][2];
slice_index = i;
}
if (routes[i][2] < min_priority) {
break;
} else if (routes[i][0].test(path)) {
result = routes[i][0].exec(path);
dfr = routes[i][1];
context = routes[i][3];
current_priority = routes[i][2];
found = true;
break;
}
}
if (i === routes.length) {
slice_index = i;
}
if (slice_index > -1) {
routes = routes.slice(slice_index);
}
if (found) {
dfr.resolveWith(
context,
result.slice(1)
);
} else {
dfr.rejectWith(context);
}
});
return dfr.promise();
},
};
$.routereset = function () {
routes = [];
current_priority = 0;
};
$.routepriority = function () {
return current_priority;
};
$.fn.route = function (method) {
var result;
if (methods.hasOwnProperty(method)) {
result = methods[method].apply(
this,
Array.prototype.slice.call(arguments, 1)
);
} else {
$.error('Method ' + method +
' does not exist on jQuery.route');
}
return result;
};
}(window, jQuery));
/*global window, jQuery */
/*!
* url.js v1.0.0
*
* Copyright 2012, Romain Courteaud
* Dual licensed under the MIT or GPL Version 2 licenses.
*
* Date: Mon Jul 16 2012
*/
"use strict";
(function (window, $) {
var hashchangeinitialized = false,
previousurl,
currentcallback,
getRawHash = function () {
return window.location.toString().split('#')[1];
},
callbackwrapper = function () {
if (previousurl !== window.location.hash) {
previousurl = window.location.hash;
if (currentcallback !== undefined) {
currentcallback();
}
}
},
timeoutwrapper = function () {
callbackwrapper();
window.setTimeout(timeoutwrapper, 500);
};
function UrlHandler() {}
UrlHandler.prototype = {
'generateUrl': function (path, options) {
var pathhash,
hash = '#',
key;
if (path !== undefined) {
hash += encodeURIComponent(path);
}
hash = hash.replace(/%2F/g, '/');
pathhash = hash;
for (key in options) {
if (options.hasOwnProperty(key)) {
if (hash === pathhash) {
hash = hash + '?';
} else {
hash = hash + '&';
}
hash += encodeURIComponent(key) +
'=' + encodeURIComponent(options[key]);
}
}
return hash;
},
'go': function (path, options) {
window.location.hash = this.generateUrl(path, options);
},
'redirect': function (path, options) {
var host = window.location.protocol + '//' +
window.location.host +
window.location.pathname +
window.location.search;
window.location.replace(host + this.generateUrl(path, options));
// window.location.replace(window.location.href.replace(/#.*/, ""));
},
'getPath': function () {
var hash = getRawHash(),
result = '';
if (hash !== undefined) {
result = decodeURIComponent(hash.split('?')[0]);
}
return result;
},
'getOptions': function () {
var options = {},
hash = getRawHash(),
subhashes,
subhash,
index,
keyvalue;
if (hash !== undefined) {
hash = hash.split('?')[1];
if (hash !== undefined) {
subhashes = hash.split('&');
for (index in subhashes) {
if (subhashes.hasOwnProperty(index)) {
subhash = subhashes[index];
if (subhash !== '') {
keyvalue = subhash.split('=');
if (keyvalue.length === 2) {
options[decodeURIComponent(keyvalue[0])] =
decodeURIComponent(keyvalue[1]);
}
}
}
}
}
}
return options;
},
'onhashchange': function (callback) {
previousurl = undefined;
currentcallback = callback;
if (!hashchangeinitialized) {
if (window.onhashchange !== undefined) {
$(window).bind('hashchange', callbackwrapper);
window.setTimeout(callbackwrapper);
} else {
timeoutwrapper();
}
hashchangeinitialized = true;
}
},
};
// Expose to the global object
$.url = new UrlHandler();
}(window, jQuery));
/* Tools to store js object in sessionStorage */ (function (window, $) {
var storejs = { 'use strict';
add: function (key, js) { /* Tools to store js object in sessionStorage */
window.sessionStorage.setItem(key, JSON.stringify(js)); var storejs = {
}, add: function (key, js) {
get: function (key) { window.sessionStorage.setItem(key, JSON.stringify(js));
return JSON.parse(window.sessionStorage.getItem(key)); },
}, get: function (key) {
extend: function (key, object) { return JSON.parse(window.sessionStorage.getItem(key));
var data = storejs.get(key); },
$.extend(data, object); extend: function (key, object) {
storejs.add(key, data); var data = storejs.get(key);
} $.extend(data, object);
} storejs.add(key, data);
}
/*************
* RESOURCES
*************/
// INSTANCE
storejs.add('instances', {
Kvm: {
status: "start_requested",
connection: {},
partition: {
public_ip: [],
tap_interface: "",
private_ip: []
},
slave: false,
children_list: [],
title: "Kvm",
software_type: "Virtual machine",
parameter: {
Custom1: "one string",
Custom2: "one float",
Custom3: "[u'abc', u'def']"
},
software_release: "http://example.com/example.cfg",
sla: {
computer_id: "COMP-0"
} }
}
});
// SOFTWARE
storejs.add('softwares', {
Kvm: {
name: 'Kvm',
image_url: 'http://www.linux-kvm.org/wiki/skins/kvm/kvmbanner-logo2.png',
thumb_url: 'http://www.system-linux.eu/public/images/kvm-logo.png',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vitae metus a est convallis pretium. Pellentesque habitant morbi tristique senectus.',
price: '1',
},
Html5as : {
name: 'Html5as',
image_url: 'http://7.mshcdn.com/wp-content/uploads/2011/01/html5-logo-1.jpg',
thumb_url: 'http://www.w3.org/html/logo/downloads/HTML5_Badge_512.png',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vitae metus a est convallis pretium. Pellentesque habitant morbi tristique senectus.',
price: '1337'
}
});
// Resources lists
storejs.add('software_list', {
list: [
'/fake/software_info/Kvm',
'/fake/software_info/Html5as',
]
});
var fakeserver = sinon.fakeServer.create(); /*************
* RESOURCES
*************/
// INSTANCE
storejs.add('instances', {
Kvm: {
status: "start_requested",
connection: {},
partition: {
public_ip: [],
tap_interface: "",
private_ip: []
},
slave: false,
children_list: [],
title: "Kvm",
software_type: "Virtual machine",
parameter: {
Custom1: "one string",
Custom2: "one float",
Custom3: "[u'abc', u'def']"
},
software_release: "http://example.com/example.cfg",
sla: {
computer_id: "COMP-0"
}
}
});
// SOFTWARE
storejs.add('softwares', {
Kvm: {
name: 'Kvm',
image_url: 'http://www.linux-kvm.org/wiki/skins/kvm/kvmbanner-logo2.png',
thumb_url: 'http://www.system-linux.eu/public/images/kvm-logo.png',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vitae metus a est convallis pretium. Pellentesque habitant morbi tristique senectus.',
price: '1'
},
Html5as : {
name: 'Html5as',
image_url: 'http://7.mshcdn.com/wp-content/uploads/2011/01/html5-logo-1.jpg',
thumb_url: 'http://www.w3.org/html/logo/downloads/HTML5_Badge_512.png',
description: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed vitae metus a est convallis pretium. Pellentesque habitant morbi tristique senectus.',
price: '1337'
}
});
// Resources lists
storejs.add('software_list', {
list: [
'/fake/software_info/Kvm',
'/fake/software_info/Html5as'
]
});
/********************* var fakeserver = sinon.fakeServer.create(),
* RESPONSE tmp = $.ajax,
*********************/
// ******* INSTANCE /*********************
var instance_list = function () { * RESPONSE
var response = {list: []}; *********************/
$.each(storejs.get('instances'), function (i, e) {
response.list.push('/fake/instance_info/' + e.title)
});
return response;
};
// list
fakeserver.respondWith('GET', '/fake/instance', function (xhr) {
var response = {list: []};
$.each(storejs.get('instances'), function (i, e) {
response.list.push('/fake/instance_info/' + e.title)
});
xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(response))
});
// Get instance info
fakeserver.respondWith("GET", /\/fake\/instance_info\/(.*)/, function (xhr, instid) {
var instances = storejs.get('instances');
if (instances.hasOwnProperty(instid)) {
xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(instances[instid]));
} else {
xhr.respond(404, { 'Content-Type': 'application/json'}, 'Not found');
}
});
// Request instance
fakeserver.respondWith("POST", '/fake/instance', function (xhr) {
var instances = storejs.get('instances'),
inst = JSON.parse(xhr.requestBody),
iadd = {},
ilist = instance_list();
iadd[inst.title] = inst;
storejs.extend('instances', iadd);
xhr.respond(201, {'Content-Type': 'application/json'}, JSON.stringify({
title: inst.title,
status: inst.status
}));
});
//********** SOFTWARE // ******* INSTANCE
// Get softwares list instance_list = function () {
fakeserver.respondWith('GET', '/fake/software', [ var response = {list: []};
200, {'Content-Type': 'application/json'}, JSON.stringify(storejs.get('software_list')) $.each(storejs.get('instances'), function (i, e) {
]); response.list.push('/fake/instance_info/' + e.title);
// Get software info });
fakeserver.respondWith("GET", /\/fake\/software_info\/(.*)/, function (xhr, softid) { return response;
var softwares = storejs.get('softwares'); };
if (softwares.hasOwnProperty(softid)) { // list
xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(softwares[softid])); fakeserver.respondWith('GET', '/fake/instance', function (xhr) {
} else { var response = {list: []};
xhr.respond(404, { 'Content-Type': 'application/json'}, 'Not found'); $.each(storejs.get('instances'), function (i, e) {
} response.list.push('/fake/instance_info/' + e.title);
}); });
xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(response));
});
// Get instance info
fakeserver.respondWith("GET", /\/fake\/instance_info\/(.*)/, function (xhr, instid) {
var instances = storejs.get('instances');
if (instances.hasOwnProperty(instid)) {
xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(instances[instid]));
} else {
xhr.respond(404, { 'Content-Type': 'application/json'}, 'Not found');
}
});
// Request instance
fakeserver.respondWith("POST", '/fake/instance', function (xhr) {
var instances = storejs.get('instances'),
inst = JSON.parse(xhr.requestBody),
iadd = {},
ilist = instance_list();
iadd[inst.title] = inst;
storejs.extend('instances', iadd);
xhr.respond(201, {'Content-Type': 'application/json'}, JSON.stringify({
title: inst.title,
status: inst.status
}));
});
//********** SOFTWARE
// Get softwares list
fakeserver.respondWith('GET', '/fake/software', [
200, {'Content-Type': 'application/json'}, JSON.stringify(storejs.get('software_list'))
]);
// Get software info
fakeserver.respondWith("GET", /\/fake\/software_info\/(.*)/, function (xhr, softid) {
var softwares = storejs.get('softwares');
if (softwares.hasOwnProperty(softid)) {
xhr.respond(200, {'Content-Type': 'application/json'}, JSON.stringify(softwares[softid]));
} else {
xhr.respond(404, { 'Content-Type': 'application/json'}, 'Not found');
}
});
var tmp = $.ajax; $.ajax = function (url, options) {
$.ajax = function(url, options){ // it will not work with cache set to false
// it will not work with cache set to false if (url.hasOwnProperty('cache')) { url.cache = true; }
if (url.hasOwnProperty('cache')) { url.cache = true; } var result = tmp(url, options);
var result = tmp(url, options); fakeserver.respond();
fakeserver.respond(); return result;
return result; };
};
$(document).slapos('store', 'host', '/fake'); $(document).slapos('store', 'host', '/fake');
}(window, jQuery));
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment