/
bootic_cart.js
700 lines (623 loc) · 19.6 KB
/
bootic_cart.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
/* bootic_cart.js, version 0.0.1
Copyright (c) 2012 Ismael Celis for Bootic S.P.A. (http://bootic.net)
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------*/
// Declare global namespace
var Bootic = Bootic || {};
// Wrap everything in a closure
;(function (window, $) {
// Events module
// =============
//
// Wrap our own objects in jQuery's .bind() and .trigger() methods.
//
// Usage:
// var MyObject = {...}
// $.extend(MyObject, Events)
// MyObject.bind('foo', function (evt, i) { alert(i)})
// MyObject.trigger('foo', [1])
var Events = {
track: function (eventName) {
if('Bootic' in window && 'track' in window.Bootic) {
Bootic.track('Bootic.Cart:' + eventName)
}
},
bind: function (eventName, fn) {
$(this).bind(eventName, fn)
return this
},
trigger: function (eventName, data) {
this.track(eventName)
$(this).trigger(eventName, data)
return this
}
}
// Cart constructor
// =========================
var Cart = function () {
this.reset(true)
}
Cart.prototype = {
// Load server cart data
// -----------------------
//
// Takes:
//
// - `fn`: a callback to be run once the server has responded successfully
//
// Triggers:
//
// - `loading`: before server response
// - `loaded`: after successfully loaded from server. Updated cart object passed as argument.
// - `error`: something went wrong with the Ajax request
load: function (fn) {
this.trigger('loading')
fn = fn || $.noop
this.request('/cart.json', {type: 'get'}, function (cartData) {
this.update(cartData)
fn(this)
this.trigger('loaded', [this])
})
return this
},
// Reset client-side cart
// -----------------------
//
// Resets product list and totals. Called on instantiation and useful for testing.
reset: function (silent) {
this.products = []
this.units = 0
this.formatted_total = '0'
this.currency = null
this.total = 0
this._productCounts = {};
this._loaded = false
if(silent) this.trigger('reset')
return this
},
// Add a product to the cart
// ---------------------------
//
// Increments quantity if product already in the cart
//
// Takes:
//
// - `variantId`: variant ID to add to cart
// - `fn`: (optional) a callback to be run with the loaded cart as an argument.
// - `opts`: (optional) options object with default overrides.
//
// Options are:
//
// - `url`: URL to load cart from (default: /cart/cart_items)
// - `type`: request method (default: 'get')
// - `quantity`: units of this product to add to cart
//
// Triggers:
//
// - `adding`: before server response
// - `added`: after successfully added to server. Added product passed as argument.
// - `error`: something went wrong with the Ajax request
add: function (variantId, fn, opts) {
fn = fn || $.noop;
var opts = $.extend({
url: '/cart/cart_items',
quantity: 1,
type: 'post',
dataType: 'json'
}, opts || {})
var data = {
cart_item: {
variant_id: variantId,
quantity: opts.quantity
}
}
opts.data = data;
//this.trigger('adding', [{variant_id: variantId}]);
this.request(opts.url, opts, function (cartData) {
this.update(cartData)
var item = this.find(variantId)
fn(item)
this.trigger('added', [item])
})
return this
},
// Find a product by variant ID
// ------------------------------
find: function (variantId, fn) {
var match = null;
this.forEach(function (item) {
if(item.variant_id == variantId){
match = item
}
})
if(fn) fn(match)
return match
},
// Find a product by product ID
// ------------------------------------------
findByProductId: function (productId, fn) {
var match = null;
this.forEach(function (item) {
if(item.product_id == productId){
match = item
}
})
if(fn) fn(match)
return match
},
// Loop all products. Emulate JavaScript's forEach
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach
forEach: function (fn, context) {
context = context || this
var i;
return this.loadAndThen(function () {
for(i = 0; i < this.products.length; i++) {
fn.call(context, this.products[i], i, this.products)
}
})
},
// Remove a product by product id
// ------------------------------
//
// Takes:
//
// - `variantId`: cart item variant ID to remove
// - `fn`: (optional) callback to be run after successful removal. Removed product passed as argument.
// - `opts`: (optional) options object
//
// Options are:
//
// - `url`: URL to DELETE (default: /cart/cart_items/:cart_item_id)
// - `type`: request method (default: 'delete')
//
// Triggers:
//
// - `removing`: before server response
// - `removed`: after successfully removed
// - `error`: something went wrong with the Ajax request
remove: function (variantId, fn, opts) {
fn = fn || $.noop
return this.loadAndThen(function () {
var item = this.find(variantId)
if(!item){this.trigger('error', ["No cart item with variant ID " + variantId]); return this}
this.trigger('removing', [item])
var opts = $.extend({
url: ('/cart/cart_items/' + item.id),
type: 'delete'
}, opts);
this.request(opts.url, opts, function (cartData) {
this.update(cartData)
if(this._productCounts[item.product_id]) {// not all variants deleted
item = this.findByProductId(item.product_id) // need to find again for calculated values. Better way?
this.trigger('added', [item])
} else { // all variants deleted
fn(item)
this.trigger('removed', [item])
}
})
})
},
// Wrap other function calls in this to make sure the cart is loaded
loadAndThen: function (fn) {
if(this._loaded) {
fn.call(this)
} else {
this.load($.proxy(fn, this))
}
return this
},
// Is the cart empty?
// -------------------
isEmpty: function () {
return !this.products || this.products.length < 1
},
// Update cart with server response
// Update unique product counts
update: function (cartData) {
this._loaded = true
this._productCounts = {}
$.extend(this, cartData)
this._calculateCounts()
this._decorateProducts()
this.trigger('updated')
},
// Issue an Ajax request
// -----------------------
//
// Takes:
//
// - `url`
// - `opts`: Ajax options object as per jQuery.ajax
// - `fn`: success callback. Will be run in the context of this instance.
//
request: function (url, opts, fn) {
opts = $.extend({
success: $.proxy(fn, this),
error: $.proxy(function (e) {
this.trigger('error', [e])
}, this)
}, opts || {})
return $.ajax(url, opts)
},
_decorateProducts: function () {
this.forEach(function (item) {
item.total_units = this._productCounts[item.product_id]
})
},
_calculateCounts: function () {
$.each(this.products, $.proxy(function (i, item) {
this._productCounts[item.product_id] = this._productCounts[item.product_id] || 0
this._productCounts[item.product_id] += item.quantity
}, this))
}
}
// Mix in bind and trigger of events
$.extend(Cart.prototype, Events);
// Assign new instance to global Bootic.Cart
Bootic.Cart = new Cart();
// HTML data API (jQuery plugin)
// ==============================
$(function () {
var formSelector = 'form[data-bootic-cart-add]';
function get(productId) {
return $('[data-bootic-productId="'+ productId +'"]')
}
Bootic.Cart
.bind('adding', function (evt, item) {
get(item.product_id).trigger('adding.bootic', [item])
})
.bind('added', function (evt, item) {
get(item.product_id).trigger('added.bootic', [item])
})
.bind('removing', function (evt, item) {
get(item.product_id).trigger('removing.bootic', [item])
})
.bind('removed', function (evt, item) {
get(item.product_id).trigger('removed.bootic', [item])
})
.bind('loaded', function (evt, cart) {
cart.forEach(function (item) {
get(item.product_id).trigger('added.bootic', [item])
})
})
// Lets remove quantity field from form. Simpler to click many times or use Ajax cart
$('input[name="cart_item[quantity]"]').remove()
// If $e is a set of radio buttons get checked one
function getUniqueValue ($e) {
if($e.is(':radio'))
return $e.filter(':checked').val()
else
return $e.val()
}
$(formSelector)
.on('added.bootic', function (evt, item) {
$(this).addClass('bootic_cart_added')
})
.on('removed.bootic', function (evt, item) {
$(this).removeClass('bootic_cart_added')
})
.on('submit', function (evt) {
var $e = $(this),
variantId = getUniqueValue($e.find('input[name="cart_item[variant_id]"]')),
qtyIput = $e.find('input[name="cart_item[quantity]"]');
if(variantId == undefined) {
evt.preventDefault()
throw "Your form must have an input of name cart_item[variant_id]"
}
var options = {
type: $e.attr('method'),
url: $e.attr('action'),
quantity: 1
}
// We need to trigger the product ID here, because we don't get it from the API until added.
$e.trigger('adding.bootic', {product_id: $e.data('bootic-cart-add')})
Bootic.Cart.find(variantId, function (item) {
if(qtyIput.length > 0) { // user is providing quantity
options.quantity = qtyIput.val()
} else if(item) { // increment by 1
options.quantity = item.quantity + 1
}
Bootic.Cart.add(variantId, null, options)
})
return false
})
Bootic.templateEngine = tim.parser({start:"<%", end:"%>", type:"text/html"})
Bootic.templates = Bootic.templates || {}; // template cache object
$("script[type='text/html'][data-template]").each(function(){
var $e = $(this)
Bootic.templates[$e.data('template')] = $e.html();
});
$.fn.booticTemplateRender = function (templateName, data) {
var content = Bootic.templateEngine(Bootic.templates[templateName], data);
$(this).empty().append(content)
return $(this)
}
})
})(window, jQuery);
/*!
* Tim
* github.com/premasagar/tim
*
*/
/*
A tiny, secure JavaScript micro-templating script.
*/
/*
by Premasagar Rose
dharmafly.com
license
opensource.org/licenses/mit-license.php
**
creates global object
tim
**
v0.3.0
*/
/*global window */
/*
TODO:
* a way to prevent a delimiter (e.g. ", ") appearing last in a loop template
* Sorted constructor for auto-sorting arrays - used for parsers -> two parsers are added, one for identifying and parsing single-tokens and one for open/close tokens - the parsers then create two new Sorted instance, one for single-token plugins and one for open/close token plugins
*/
var tim = (function createTim(initSettings) {
"use strict";
var settings = {
start: "{{",
end: "}}",
path: "[a-z0-9_][\\.a-z0-9_]*" // e.g. config.person.name
},
templates = {},
filters = {},
stopThisFilter, pattern, initialized, undef;
/////
// Update cached regex pattern
function patternCache() {
pattern = new RegExp(settings.start + "\\s*(" + settings.path + ")\\s*" + settings.end, "gi");
}
// settingsCache: Get and set settings
/*
Example usage:
settingsCache(); // get settings object
settingsCache({start:"<%", end:"%>", attr:"id"}); // set new settings
*/
function settingsCache(newSettings) {
var s;
if (newSettings) {
for (s in newSettings) {
if (newSettings.hasOwnProperty(s)) {
settings[s] = newSettings[s];
}
}
patternCache();
}
return settings;
}
// Apply custom settings
if (initSettings) {
settingsCache(initSettings);
} else {
patternCache();
}
/////
// templatesCache: Get and set the templates cache object
/*
Example usage:
templatesCache("foo"); // get template named "foo"
templatesCache("foo", "bar"); // set template named "foo" to "bar"
templatesCache("foo", false); // delete template named "foo"
templatesCache({foo:"bar", blah:false}); // set multiple templates
templatesCache(false); // delete all templates
*/
function templatesCache(key, value) {
var t;
switch (typeof key) {
case "string":
if (value === undef) {
return templates[key] || "";
} else if (value === false) {
delete templates[key];
} else {
templates[key] = value;
}
break;
case "object":
for (t in key) {
if (key.hasOwnProperty(t)) {
templatesCache(t, key[t]);
}
}
break;
case "boolean":
if (!key) {
templates = {};
}
break;
}
return templates;
}
function extend(obj1, obj2) {
var key;
for (key in obj2) {
if (obj2.hasOwnProperty(key)) {
obj1[key] = obj2[key];
}
}
return obj1;
}
/////
// FILTERS
function sortByPriority(a, b) {
return a[1] - b[1];
}
// Add filter to the stack
function addFilter(filterName, fn, priority) {
var fns = filters[filterName];
if (!fns) {
fns = filters[filterName] = [];
}
fns.push([fn, priority || 0]);
fns.sort(sortByPriority);
return fn;
}
function applyFilter(filterName, payload) {
var fns = filters[filterName],
args, i, len, substituted;
if (fns) {
args = [payload];
i = 2;
len = arguments.length;
for (; i < len; i++) {
args.push(arguments[i]);
}
i = 0;
len = fns.length;
for (; i < len; i++) {
args[0] = payload;
substituted = fns[i][0].apply(null, args);
if (payload !== undef && substituted !== undef) {
payload = substituted;
}
if (stopThisFilter) {
stopThisFilter = false;
break;
}
}
}
return payload;
}
// Router for adding and applying filters, for Tim API
function filter(filterName, payload) {
return (typeof payload === "function" ? addFilter : applyFilter).apply(null, arguments);
}
filter.stop = function () {
stopThisFilter = true;
};
/////
// Merge data into template
/*
// simpler alternative, without support for iteration:
template = template.replace(pattern, function(tag, token){
return applyFilter("token", token, data, template);
});
*/
// TODO: all an array to be passed to tim(), so that the template is called for each element in it
function substitute(template, data) {
var match, tag, token, substituted, startPos, endPos, templateStart, templateEnd, subTemplate, closeToken, closePos, key, loopData, loop;
while ((match = pattern.exec(template)) !== null) {
token = match[1];
substituted = applyFilter("token", token, data, template);
startPos = match.index;
endPos = pattern.lastIndex;
templateStart = template.slice(0, startPos);
templateEnd = template.slice(endPos);
// If the final value is a function call it and use the returned
// value in its place.
if (typeof substituted === "function") {
substituted = substituted.call(data);
}
if (typeof substituted !== "boolean" && typeof substituted !== "object") {
template = templateStart + substituted + templateEnd;
} else {
subTemplate = "";
closeToken = settings.start + "/" + token + settings.end;
closePos = templateEnd.indexOf(closeToken);
if (closePos >= 0) {
templateEnd = templateEnd.slice(0, closePos);
if (typeof substituted === "boolean") {
subTemplate = substituted ? templateEnd : '';
} else {
for (key in substituted) {
if (substituted.hasOwnProperty(key)) {
pattern.lastIndex = 0;
// Allow {{_key}} and {{_content}} in templates
loopData = extend({
_key: key,
_content: substituted[key]
}, substituted[key]);
loopData = applyFilter("loopData", loopData, loop, token);
loop = tim(templateEnd, loopData);
subTemplate += applyFilter("loop", loop, token, loopData);
}
}
subTemplate = applyFilter("loopEnd", subTemplate, token, loopData);
}
template = templateStart + subTemplate + template.slice(endPos + templateEnd.length + closeToken.length);
} else {
throw "tim: '" + token + "' not closed";
}
}
pattern.lastIndex = 0;
}
return template;
}
// TIM - MAIN FUNCTION
function tim(template, data) {
var templateLookup;
// On first run, call init plugins
if (!initialized) {
initialized = 1;
applyFilter("init");
}
template = applyFilter("templateBefore", template);
// No template tags found in template
if (template.indexOf(settings.start) < 0) {
// Is this a key for a cached template?
templateLookup = templatesCache(template);
if (templateLookup) {
template = templateLookup;
}
}
template = applyFilter("template", template);
// Substitute tokens in template
if (template && data !== undef) {
template = substitute(template, data);
}
template = applyFilter("templateAfter", template);
return template;
}
// Get and set settings, e.g. tim({attr:"id"});
tim.settings = settingsCache;
// Get and set cached templates
tim.templates = templatesCache;
// Create new Tim function, based on supplied settings, if any
tim.parser = createTim;
// Add new filters and trigger existing ones. Use tim.filter.stop() during processing, if required.
tim.filter = filter;
/////
// dotSyntax default plugin: uses dot syntax to parse a data object for substitutions
addFilter("token", function (token, data, tag) {
var path = token.split("."),
len = path.length,
dataLookup = data,
i = 0;
for (; i < len; i++) {
dataLookup = dataLookup[path[i]];
// Property not found
if (dataLookup === undef) {
throw "tim: '" + path[i] + "' not found" + (i ? " in " + tag : "");
}
// Return the required value
if (i === len - 1) {
return dataLookup;
}
}
});
return tim;
}()); /*jslint browser: true, onevar: true, undef: true, eqeqeq: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: true */