Nepal on Rails

millisami's rants!

Drag N Drop With Emberjs, Part 2

This is the part 2 for the earlier post Drag and drop with Emberjs. In this post, our objective is to:

  • Update the Total cart price when a product is dropped into the cart
  • List the products added in the cart

When a product is dropped over the cart, we need some kind of array into which we’d push the record. So, lets set the line_items array in the controller to hold the cart products. Create a controller file:

app/controllers/index.coffee
1
2
module.exports = App.IndexController = Ember.ArrayController.extend
  line_items: []

Now whenever a product is dropped into the cart, lets push that object.

1
@get('controller').get('line_items').pushObject(record)

So now our cart view looks:

app/views/cart.coffee
1
2
3
4
5
6
7
8
9
module.exports = App.CartView = Ember.View.extend
  templateName: 'cart'
  classNames: ['basket']
  dragOver: (ev) ->
    ev.preventDefault()
  drop: (ev) ->
    id = ev.dataTransfer.getData('text/data')
    record = @get('controller').findProperty('id', Number(id))
    @get('controller').get('line_items').pushObject(record)

To list the items added into the cart, we need to update our cart template.

app/templates/cart.hbs
1
2
3
4
5
6
7
<div class="line_items">
  {{#each line_item in line_items}}
    <div class="line_item">
      {{line_item.title}} <span>{{line_item.price}}</span>
    </div>
  {{/each}}
</div>

Now, whenever a product is dropped into the basket, the item is listed in the view.

To keep the track of the total price, we need to declare a computed property into the controller that computes the total price of the basket. So, in the cart template, lets add total_price

app/templates/cart.hbs
1
2
3
4
5
6
7
8
9
10
11
12
<div class="total">{{total_price}}</div>
<div class="shop_cart">
  <span>Drop the product here</span>
</div>

<div class="line_items">
  {{#each line_item in line_items}}
    <div class="line_item">
      {{line_item.title}} <span>{{line_item.price}}</span>
    </div>
  {{/each}}
</div>

And add this into the index controller.

app/controllers/index.coffee
1
2
3
4
5
6
7
8
9
10
module.exports = App.IndexController = Ember.ArrayController.extend
  line_items: []

  total_price: (->
    total = 0
    if @get('line_items').length > 0
      @get('line_items').forEach (line_item) ->
        total += line_item.price
    total
  ).property('line_items.@each')

This concludes the bare minimum we can do to achieve the drag and drop functionality with Emberjs. There are many things that can be added to extend the functionality of this app, but its out of the scope of this post.

I’ve updated the repo where it has thing like, filtering the items and its quantity with some styles.

In the next post, I’ll be writing on how to deploy the ember app built with rapid development workflow onto heroku as node app to host the production app.

To stay updated, just follow @nepalonrails

Comments