A complete newbie to Emberjs here and a sort of newbie to web development. I'm trying to build a very simple e-tailer website in order to get familiar with Ember. The process where I'm getting stuck is getting my product model to get added to cart.
The details of the project: emberjs: 1.13.2
ember-data: 1.13.4
ember-cli: 0.2.7
The backend is being mocked by ember-cli-mirage
The code is as follows:
models/product.js
import DS from 'ember-data';
export default DS.Model.extend({
name: DS.attr('string'),
description: DS.attr('string'),
category: DS.attr('string'),
price: DS.attr('number'),
quantityInStock: DS.attr('number'),
imageUrl: DS.attr('string')
});
models/item.js
import DS from 'ember-data';
export default DS.Model.extend({
product: DS.belongsTo('product'),
cart: DS.belongsTo('cart'),
quantity: DS.attr('number'),
subTotal: function() {
return this.get('product').get('price') * this.get('quantity');
}.property('product', 'quantity')
});
models/cart.js
import DS from 'ember-data';
export default DS.Model.extend({
items: DS.hasMany('item')
});
controllers/products.js
import Ember from 'ember';
export default Ember.Controller.extend({
needs: ['cart'],
cart: Ember.computed.alias('controllers.cart'),
actions: {
addToCart: function(product) {
this.get('cart').add(product);
}
}
});
controllers/cart.js
import Ember from 'ember';
export default Ember.Controller.extend({
add: function(product) {
}
});
What I can't figure out is how to get the cart controller to handle the action. I think the code is supposed to do this:
- find the cart model from the data store
- check to see if the item being added to the cart is already in the cart
- if it is: increment its property by 1
- if it is not: create a new item, make it belong to the cart, give it the product, give it a quantity of 1. Then, save it.
- Finally, add this item to the cart. Save the cart to the backend.
Some notes, thoughts & other problems
Note #1: I only have routes to handle product and cart on the backend (I don't see why I would handle item since it would be in the cart hash).
But, saving an item makes a call to the back-end. I'm guessing I should save the item in localstorage? Not sure how to go about doing that in the latest version of ember-data.
Note #2: I don't use any dynamic urls. all the products load on a single page. There are only two routes: products and cart.
Note #3: the item
model is a line item.
Note #4: I'm not even sure if this is the best way to handle it. Should I just load multiple models on the product route. Would that simplify it?
I'm not sure if I should include any other code but the github is here:
Thanks a lot!
Aucun commentaire:
Enregistrer un commentaire