Skip to content

Instantly share code, notes, and snippets.

@jparbros
Created February 11, 2012 04:52
Show Gist options
  • Save jparbros/1796510 to your computer and use it in GitHub Desktop.
Save jparbros/1796510 to your computer and use it in GitHub Desktop.
backbone.js ejemplo 2
window.Variant = Backbone.Model.extend({
url: function() {
if (this.id != null) {
return 'variants/' + this.id;
} else {
return 'variants';
}
},
addToCart: function() {
return alert('I was added to cart ' + this.id);
}
});
window.VariantCollection = Backbone.Collection.extend({
model: Variant,
url: function() {
return window.product_id + '/variants';
}
});
window.Variants = new VariantCollection();
window.VariantView = Backbone.View.extend({
tagName: 'option',
render: function() {
var source, template;
source = $('#variant-option-template').html();
template = Handlebars.compile(source);
$(this.el).html(template(this.model.toJSON()));
$(this.el).attr('value', this.model.id);
return this;
}
});
window.ShoppingCartItem = Backbone.Model.extend({
url: function() {
return '/store/shopping_cart_items';
}
});
window.AddToCartApp = Backbone.View.extend({
el: $('#add-to-cart'),
events: {
'click a.add-to-cart': 'addVariantToCart'
},
initialize: function() {
_.bindAll(this, 'addOne', 'addAll', 'addVariantToCart');
Variants.bind('add', this.addOne);
Variants.bind('reset', this.addAll);
return Variants.fetch();
},
addOne: function(variant) {
var variant_select, variant_view;
variant_view = new VariantView({
model: variant
});
variant_select = this.el.find('select');
return variant_select.append(variant_view.render().el);
},
addAll: function() {
return Variants.each(this.addOne);
},
addVariantToCart: function() {
var item, val;
val = this.$('select').val();
item = new ShoppingCartItem({
'variant_id': val,
'items_in_cart': 0
});
return Backbone.sync('create', item, {
success: this.updateCartCounter
});
},
updateCartCounter: function(response) {
if (response.status === 'added_to_wait_list') {
$("#flash").html("<div class='info'>The item was added to your wait list <a class='close' href='#'></a> </div>");
return $('#flash .close').bind('click', function(e) {
return $(e.target).parent().fadeOut('slow');
});
} else {
shoppingCartItemsCounter.set({
count: response.message
});
return window.shoppingCartPopup();
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment