var summaryModule = (function(postal, $) { var summaryTemplate = "#summary-tmpl", summaryItemTemplate = "#summary-item-tmpl", qtySummarySelector = "#summary-list", orderTotalSummarySelector = "#summary-list", wireUpSummary = function(summary) { postal.subscribe("summary", "init", _.bind(summary.init, summary)); }, wireUpQuantitySummary = function(qtySummary) { postal.subscribe("summary", "qtychange", function(msg) { qtySummary.qty++; qtySummary.notifyOfChange(); }); postal.subscribe("summary", "init", function() { qtySummary.qty = 0; qtySummary.notifyOfChange(); }); }, wireUpOrderTotalSummary = function(ordTtlSummary) { postal.subscribe("summary", "ordertotalchange", function(msg) { ordTtlSummary.total += msg.price; ordTtlSummary.notifyOfChange(); }); postal.subscribe("summary", "init", function() { ordTtlSummary.total = 0; ordTtlSummary.notifyOfChange(); }); }, SummaryPrototype = { init: function() { this.items = [ new QuantitySummary(new SummaryItemDomProxy(qtySummarySelector), "summary-qty"), new OrderTotalSummary(new SummaryItemDomProxy(orderTotalSummarySelector), "summary-total") ]; this.proxy.render(this); } }, Summary = function(domProxy) { this.items = []; this.proxy = domProxy; wireUpSummary(this); }, SummaryDomProxyPrototype = { render: function(model) { $(this.selector).html(_.template($(summaryTemplate).html(), model)); $.each(model.items, function(idx, item){ item.notifyOfChange(); }); } }, SummaryDomProxy = function(selector) { this.selector = selector; }, QuantitySummaryPrototype = { notifyOfChange: function() { this.proxy.render({ msg: this.qty + " item(s) selected.", id: this.id }); } }, QuantitySummary = function(domProxy, id) { this.qty = 0; this.id = id; this.proxy = domProxy; wireUpQuantitySummary(this); }, OrderTotalSummaryPrototype = { notifyOfChange: function() { this.proxy.render({ msg: "Current Order Total: $" + this.total.toFixed(2), id: this.id }); } }, OrderTotalSummary = function(domProxy, id) { this.total = 0; this.id = id; this.proxy = domProxy; wireUpOrderTotalSummary(this); }, SummaryItemDomProxyPrototype = { render: function(model) { var target = $("#" + model.id), rendered = _.template($(summaryItemTemplate).html(), model); if(target.length === 0) { $(this.selector).append(rendered); } else { target.replaceWith(rendered); } } }, SummaryItemDomProxy = function(selector) { this.selector = selector; }; Summary.prototype = SummaryPrototype; SummaryDomProxy.prototype = SummaryDomProxyPrototype; QuantitySummary.prototype = QuantitySummaryPrototype; OrderTotalSummary.prototype = OrderTotalSummaryPrototype; SummaryItemDomProxy.prototype = SummaryItemDomProxyPrototype; return { start: function(selector) { return new Summary(new SummaryDomProxy(selector)); } } })(postal, jQuery);