Skip to content

Instantly share code, notes, and snippets.

@Soben
Created October 28, 2015 16:00
Show Gist options
  • Save Soben/4cba8ff3f87eaf653bb2 to your computer and use it in GitHub Desktop.
Save Soben/4cba8ff3f87eaf653bb2 to your computer and use it in GitHub Desktop.
class MiniCartHandler
constructor : (@jQuery, @popupElement, @navElement) ->
@cartCount = @popupElement.data('itemcount')
@cartLimit = @popupElement.data('itemlimit')
@cartLimit ?= 5
@cartDisplay = @popupElement.find('.cart-items')
@navElement.on 'click', @popupOnClick
@checkForAndUpdateExtraProductsWarning()
popupOnClick : (e) =>
e.preventDefault()
@popupToggle()
addProduct : (item) ->
@cartHide()
@clearNewProducts()
@clearEmptyNotice()
@cartDisplay.prepend(@buildCartItemHTML(item))
@incrementCartCount()
@cartShow()
getExtraItemsDOM : (remaining) ->
domObject = @cartDisplay.find('.notice-cart-extra')
if domObject.length <= 0
@cartDisplay.append(@buildExtraItemsHTML(remaining))
domObject = @cartDisplay.find('.notice-cart-extra')
return domObject
buildCartItemHTML : (item) ->
# name : 'example product'
# image : 'http://'
# href : 'http://'
# option : 'product option'
# quantity : 1
$ """
<article class="cart-item new-item">
<img src="#{item.image}" alt="#{item.name}" />
<div>
<p class="title">#{item.quantity}x <a href="#{item.href}">#{item.name}</a></p>
<p class="option-details">#{item.option}</p>
</div>
</article>
"""
buildExtraItemsHTML : (remaining) ->
$ """
<div class="notice-cart-extra">
plus <span class="cart-count"></span> more items(s)
</div>
"""
clearNewProducts : () ->
@cartDisplay.find('article').removeClass('new-item')
@cartDisplay.find('article .option-details').remove()
clearEmptyNotice : () ->
@cartDisplay.find('.notice-empty').removeClass('new-item')
popupToggle : () ->
if ( @popupElement.hasClass('hidden') )
@cartShow()
else
@cartHide()
cartShow : () ->
@popupElement.removeClass('hidden')
cartHide : () ->
@popupElement.addClass('hidden')
incrementCartCount : () ->
@cartCount++
@popupElement.data('itemcount', @cartCount)
@navElement.find('.cart-count').html(@cartCount)
@checkForAndUpdateExtraProductsWarning()
checkForAndUpdateExtraProductsWarning : () ->
if @cartCount > @cartLimit
remaining = @cartCount - @cartLimit
moreItemsDom = @getExtraItemsDOM(remaining)
moreItemsDom.find('.cart-count').html(remaining);
jQuery ($) ->
window.mini_cart =
new MiniCartHandler($, $('#mini-cart'), $('.cart-toggle'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment