var baseUrl = '';
(function($) {
$(document).ready(function() {
var $main = $('#main');
//
// function home() {
// $('#main')
// }
//
// function showAlert(type, text) {
// $('#alert')
// .removeClass('success')
// }
var routeMap = {
about: {
data: function(cb) {
$.get(baseUrl + '/data/about.html', cb);
},
controller: function(aboutHtml) {
console.log('about', aboutHtml);
$('#main').html(aboutHtml);
}
},
welcome: {
data: function(cb) {
console.log('get data for welcome');
$.get(baseUrl + '/data/products.json', function(data) {
console.log('welcome.data.success', data);
cb(data);
}, 'json');
},
controller: function(products) {
console.log('controller', arguments, products);
products.forEach(product => {
$main.append('
' +
'

' +
'
' + product.name + '
' +
'
');
})
}
},
cart: {
data: function(cb) {
$.get(baseUrl + '/data/products.json', function(products) {
console.log('products', products);
$.get(baseUrl + '/data/cart.json', function(cart) {
console.log('cart', cart);
// console.log(cb.toString());
cb({products, cart});
});
});
},
controller: function(data) {
// console.log('controller', arguments, data);
// $('#main').html(data.products.length);
var products = data.products;
var cart = data.cart;
console.log(products);
var $table = $('' +
' | ' +
'Product ref | ' +
'Product name | ' +
'Qty. | ' +
'Unit price | ' +
'Price | ' +
'
').appendTo($main);
var total = 0.0;
cart.forEach(function(item) {
console.log('cart item', item);
var product = _.find(products, {
id: item.productId
});
total += item.quantity * product.price;
$table.append('' +
' | ' +
'' + product.productRef + ' | ' +
'' + product.name + ' | ' +
'' + item.quantity + ' | ' +
'' + product.price + '€ | ' +
'' + item.quantity * product.price + '€ | ' +
'
'
)
});
$table.append(' | ' +
'' +total + '€ |
'
);
}
}
};
function router(e) {
var hash = window.location.hash;
hash = hash ? hash.substr(1) : 'welcome';
console.log('hash changed', hash);
var existingRoutes = Object.keys(routeMap);
if(existingRoutes.indexOf(hash) === -1) {
console.log('error', 'route does not exist');
}
var routeHandler = routeMap[hash];
if(
typeof routeHandler.data !== 'function' ||
typeof routeHandler.controller !== 'function'
) {
console.log('Error, route handler for "' + hash + '" is invalid', routeHandler);
}
routeHandler.data(function(data) {
// console.log('got data', hash, data);
$main.empty();
routeHandler.controller(data)
});
}
window.addEventListener('hashchange', router);
router();
// console.log('ok loading products...');
// $.get('/data/products.json?ts=' + Date.now(), function(data) {
// alert('done');
// // console.log('got products', data);
// }, 'json');
});
})(jQuery);