PageRenderTime 45ms CodeModel.GetById 20ms RepoModel.GetById 1ms app.codeStats 0ms

/cart.js

https://bitbucket.org/homanchou/backbone_cart
JavaScript | 62 lines | 49 code | 13 blank | 0 comment | 1 complexity | b8ac3e7b405b1f99f879a580c8be4dfb MD5 | raw file
  1. $(function() {
  2. LineItem = Backbone.Model.extend({
  3. });
  4. LineItemView = Backbone.View.extend({
  5. model:LineItem,
  6. tagName: "tr",
  7. template: _.template("<td><%= sku %></td><td><input name='li_qty' class='li_qty' value='<%= qty %>'></td><td><%= unit_price %></td><td><%= line_item_type %></td><td>weight: <%= weight %> dimensions: <%= dim_length %> x <%= dim_width %> x <%= dim_height %></td><td align='right'><%= qty * unit_price %></td>"),
  8. render: function() {
  9. this.$el.html(this.template(this.model.toJSON()));
  10. return this;
  11. },
  12. initialize: function() {
  13. this.model.bind('change', this.render, this);
  14. this.model.bind('destroy', this.remove,this);
  15. },
  16. events: {
  17. 'change':'detectChange'
  18. },
  19. detectChange:function(){
  20. this.model.set({qty: this.$('.li_qty').val()});
  21. if (this.model.get('qty') === "0") {
  22. this.model.destroy();
  23. }
  24. }
  25. });
  26. LineItems = Backbone.Collection.extend({});
  27. AppView = Backbone.View.extend({
  28. el: 'body',
  29. initialize: function(){
  30. this.lineItems = new LineItems;
  31. this.lineItems.bind('add', this.renderNewSku, this);
  32. this.lineItems.bind('add remove', this.recalcShippingOptions, this);
  33. },
  34. events: {
  35. 'click #add_to_cart': 'createLineItemModel'
  36. },
  37. createLineItemModel: function(){
  38. this.lineItems.add({sku: $('#sku').val(), qty:$('#qty').val(), unit_price: $('#unit_price').val(), line_item_type:$('#line_item_type').val(), weight:$('#weight').val(), dim_length:$('#dim_length').val(),dim_width:$('#dim_width').val(),dim_height:$('#dim_height').val() });
  39. },
  40. renderNewSku: function(skuDetails) {
  41. var view = new LineItemView({model: skuDetails});
  42. $('#cart table').append(view.render().$el);
  43. },
  44. recalcShippingOptions: function(){
  45. console.log('recalc shipping options based on ' + this.lineItems.length + " line items");
  46. }
  47. });
  48. app = new AppView();
  49. });