Create a gist now

Instantly share code, notes, and snippets.

@vinaynair /View.js
Last active Aug 29, 2015

What would you like to do?
Simple JS Logging and AJAX JQuery wrapper
//Configuration
//=============
var rootUrl='/rest/services/cache';
var infoEnabled=true;
var debugEnabled=false;
//Functions
//=========
var LOG = {
info:function(msg){
if(infoEnabled) console.log("[INFO] "+msg);
},
debug:function(msg){
if(debugEnabled) console.log("[DEBUG] "+msg);
}
};
var AJAX={
GET:function(url,f){
$.ajax({
type: 'GET',
url: rootUrl+url,
async: false,
contentType: "application/json",
success: function(r) {
LOG.info("Received response="+JSON.stringify(r));
f(r);
},
error: function(e) {
console.log(e.message);
}
});
},
POST:function(url,jsObjectToPost,f){
$.ajax({
type: 'POST',
url: rootUrl+url,
async: false,
contentType: "application/json",
data:JSON.stringify(jsObjectToPost),
success: function(r) {
LOG.info("Received response="+r);
f(r);
},
error: function(e) {
console.log("error="+e.message);
}
});
}
};
//View
var View={
processProductIDs:function(ids){
LOG.info("updating view with product IDs="+ids);
$("#productsTable tr").not(":first").remove();
$("#cartTable tr").not(":first").remove();
for(var index in ids){
AJAX.GET("/productData/"+ids[index],View.addProductToTable);
}
},
addProductToTable:function(product){
LOG.info("adding product ="+JSON.stringify(product)+" to user "+userID);
if(product==null)return;
$("#productsTable tbody").after(
'<tr><td>'+product.id+'</td>'+
'<td>'+product.name+'</td>'+
'<td>'+product.price+'</td>'+
'<td><button type="button" class="btn btn-success" aria-label="Left Align" onclick="shoppingUtil.addProductToCart(\''+userID+'\','+product.id+')">'+
'<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>'+
'</button>'+
'</td>'+
'</tr>');
},
addProductToCart:function(userID,productID){
LOG.info("adding product to cart ="+JSON.stringify(productID));
if(productID==null)return;
AJAX.GET("/productData/"+productID,
function(product){
$("#cartTable tbody").after(
'<tr>'+
'<td>'+product.name+'</td>'+
'<td>'+product.price+'</td>'+
'<td><button type="button" class="btn btn-danger" aria-label="Left Align" onclick="View.removeProduct(this,\''+product.name+'\','+product.price+')">'+
'<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>'+
'</button>'+
'</td>'+
'</tr>');
View.updateSummary(product.price);
productsInCart.push(product.name);
}
);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment