Skip to content

Instantly share code, notes, and snippets.

@mayfer
Created November 12, 2015 19:27
Show Gist options
  • Save mayfer/43e4189a9338d44c00ee to your computer and use it in GitHub Desktop.
Save mayfer/43e4189a9338d44c00ee to your computer and use it in GitHub Desktop.
var ShoppingCart = function(parent) {
var self = this;
self.parent = parent;
this.state = {
"items": {
"Chicken": 79.99,
"Horse": 1299.99,
},
"cart": {
},
};
this.close = function() {
self.parent.slideUp(2000);
}
this.render = function() {
var cart = this.state.cart;
var items = this.state.items;
cart_items = [];
for(key in cart) {
item = {
name: key,
count: cart[key],
price: items[key],
}
cart_items.push(item);
}
var contents = microtemplates($("#summary_tmpl").text(), {items: cart_items});
self.parent.html(contents);
}
this.init = function() {
var cart = this.state.cart;
var items = this.state.items;
self.parent.on("click", ".item a", function(e){
// first get parent
var item = $(this).parents(".item");
var name = item.find(".name").text();
var price = items[name];
if(cart[name]) {
cart[name] += 1;
} else {
cart[name] = 1;
}
self.render();
});
self.parent.on('click', '.minus', function(e) {
var item = $(this).closest(".item");
var name = item.find(".name").text();
cart[name] -= 1;
self.render();
});
}
}
<html>
<head>
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="./microtemplates.js"></script>
<script src="./cart.js"></script>
<script type="text/html" id="summary_tmpl">
<div class="shop">
<div class="items">
<h3>Pet Store</h3>
<div class="item">
<div class="name">Chicken</div>
<div class="price">$79.99</div>
<div><a>+ Add to cart</a></div>
</div>
<div class="item">
<div class="name">Horse</div>
<div class="price">$1299.99</div>
<div><a>+ Add to cart</a></div>
</div>
<div class="item">
<div class="name">Flea</div>
<div class="price">$0.49</div>
<div><a>+ Add to cart</a></div>
</div>
</div>
</div>
<div class="summary">
<h4>Your Cart</h4>
<% if(items.length > 0) { %>
<div class="items">
<div class='item'>
<% items.forEach(function(item) { %>
<%= item.count %> &times; <span class="name"><%= item.name %></span>: $<%= item.price %>
<a class='plus'>+</a> / <a class='minus'>-</a></div>
<% }); %>
</div>
</div>
<div class="tax">
Tax: $17.22 (15%)
</div>
<div class="total">
Total: $266.22
</div>
<% } else { %>
Your cart is empty
<% } %>
</div>
</script>
<script>
$(function() {
setTimeout(function() {
cart = new ShoppingCart($("#one"));
cart.init();
cart.render();
cart2 = new ShoppingCart($("#two"));
cart2.init();
cart2.render();
}, 2000);
});
</script>
<style>
body { font-family: "PT Sans"; }
#wrapper { width: 800px; margin: 100px auto; }
.shop .item { display: inline-block; padding: 10px; background: #fafafa; }
a { color: #0af; cursor: pointer; }
</style>
</head>
<body>
<div id="wrapper">
HELLOOOOO
<div id="one">
</div>
<div id="two">
</div>
</div>
</body>
</html>
// Simple JavaScript Templating
// Paul Miller (http://paulmillr.com)
// http://underscorejs.org
// (c) 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
(function(globals) {
// By default, Underscore uses ERB-style template delimiters, change the
// following template settings to use alternative delimiters.
var settings = {
evaluate : /<%([\s\S]+?)%>/g,
interpolate : /<%-([\s\S]+?)%>/g,
escape : /<%=([\s\S]+?)%>/g
};
// When customizing `templateSettings`, if you don't want to define an
// interpolation, evaluation or escaping regex, we need one that is
// guaranteed not to match.
var noMatch = /(.)^/;
// Certain characters need to be escaped so that they can be put into a
// string literal.
var escapes = {
"'": "'",
'\\': '\\',
'\r': 'r',
'\n': 'n',
'\t': 't',
'\u2028': 'u2028',
'\u2029': 'u2029'
};
var escaper = /\\|'|\r|\n|\t|\u2028|\u2029/g;
// List of HTML entities for escaping.
var htmlEntities = {
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#x27;'
};
var entityRe = new RegExp('[&<>"\']', 'g');
var escapeExpr = function(string) {
if (string == null) return '';
return ('' + string).replace(entityRe, function(match) {
return htmlEntities[match];
});
};
var counter = 0;
// JavaScript micro-templating, similar to John Resig's implementation.
// Underscore templating handles arbitrary delimiters, preserves whitespace,
// and correctly escapes quotes within interpolated code.
var tmpl = function(text, data) {
var render;
// Combine delimiters into one regular expression via alternation.
var matcher = new RegExp([
(settings.escape || noMatch).source,
(settings.interpolate || noMatch).source,
(settings.evaluate || noMatch).source
].join('|') + '|$', 'g');
// Compile the template source, escaping string literals appropriately.
var index = 0;
var source = "__p+='";
text.replace(matcher, function(match, escape, interpolate, evaluate, offset) {
source += text.slice(index, offset)
.replace(escaper, function(match) { return '\\' + escapes[match]; });
if (escape) {
source += "'+\n((__t=(" + escape + "))==null?'':escapeExpr(__t))+\n'";
}
if (interpolate) {
source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'";
}
if (evaluate) {
source += "';\n" + evaluate + "\n__p+='";
}
index = offset + match.length;
return match;
});
source += "';\n";
// If a variable is not specified, place data values in local scope.
if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n';
source = "var __t,__p='',__j=Array.prototype.join," +
"print=function(){__p+=__j.call(arguments,'');};\n" +
source + "return __p;\n//# sourceURL=/microtemplates/source[" + counter++ + "]";
try {
render = new Function(settings.variable || 'obj', 'escapeExpr', source);
} catch (e) {
e.source = source;
throw e;
}
if (data) return render(data, escapeExpr);
var template = function(data) {
return render.call(this, data, escapeExpr);
};
// Provide the compiled function source as a convenience for precompilation.
template.source = 'function(' + (settings.variable || 'obj') + '){\n' + source + '}';
return template;
};
tmpl.settings = settings;
if (typeof define !== 'undefined' && define.amd) {
define([], function () {
return tmpl;
}); // RequireJS
} else if (typeof module !== 'undefined' && module.exports) {
module.exports = tmpl; // CommonJS
} else {
globals.microtemplates = tmpl; // <script>
}
})(this);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment