CoffeeScript
HTML
<ul>
<li class="product" data-id="1">Product 1</li>
<li class="product" data-id="2">Product 2</li>
<li class="product" data-id="3">Product 2</li>
<li class="product" data-id="4">Product 3</li>
<li class="product" data-id="5">Product 4</li>
<div id="submit">Create Purchase</div>
</ul>
<h4>check logs by opening the console</h4>
CSS
.console {
background-color: grey;
color: white;
height: 500px;
}
h4 {
color: red;
width: 100%;
text-align: center;
}
CoffeeScript
class Purchase
constructor: () ->
# on $(document).ready a new Purchase is created
@submit = $('#submit')
# for each div.product a new Product instance is created
@products = $.map $('.product'), (product, i) ->
new Product(product)
# @onSubmit()
# Comment 3)
# My issue here is how to I access the @items from the Purchase class and call @serialize()?
# onSubmit: ->
#@submit.click ->
#console.log Product.serialize()
class Product
@items: []
constructor: (product) ->
@product = $(product)
@id = @product.data("id")
@submit = $('#submit')
@setEvent()
@onSubmit()
setEvent: ->
@product.click =>
# Comment 1)
# Product.items is a class variable of Product
# because I need to access it from the Purchase class and send post request
# when the user clicks on the $('submit') button
Product.items.push new Item(@id)
console.log(Product.items)
onSubmit: ->
@submit.click ->
# Comment 2)
# This works as you can see, but we have 4 products and this operation will
# be performed 4 times. I want to achieve this in the Purchase object so it is perfomed only
# once, by creating a sumit event handler in Purchase
console.log(Product.serialize())
@serialize: =>
items_attributes: (item.serialize() for item in Product.items)
class Item
constructor: (@product_id)->
serialize: =>
product_id: @product_id.toString()
$(document).ready ->
new Purchase()