I have an instance-initializer (below) for a shopping cart. The cart is an ember-data model because I am persisting to the back end. I am wanting all instances of my ember app to have a cart ID assigned before doing anything else.
I know the ideal is async, but item prices on the site are dependent on the cart. I am finding it would be easier to handle both the front end and the back end if I can depend on the cart always existing.
How can I tell ember to not do anything else until the cart instance-initializer completes and the ember-data cart model resolves?
My instance initializer:
export function initialize(appInstance) {
let CartService = appInstance.factoryFor('service:cart');
let cart = CartService.create();
// check if there's a cart id present in localStorage
if (window.localStorage) {
if (window.localStorage.getItem('cart')) {
//previous cart id found
cart.loadCart(window.localStorage.getItem('cart'))
} else {
// no LS cart found, create a new one
cart.createCart();
}
}
appInstance.register('cart:main', cart, { instantiate: false });
appInstance.inject('route', 'cart', 'cart:main');
appInstance.inject('controller', 'cart', 'cart:main');
appInstance.inject('component', 'cart', 'cart:main');
}
export default {
name: 'cart',
initialize
};
It handles two scenarios: a cart exists in localStorage, or no cart exists, create a new one. Those two methods are:
// cart service methods
loadCart(jsonCart) {
// called from instance-initializer when a previous cart is found in localStorage
let incomingCart = JSON.parse(jsonCart); // the raw cart in LS
this.get('store').findRecord('cart', incomingCart.cartid).then(cart => {
cart.setProperties(incomingCart);
cart.save();
set(this, 'cartObj', cart);
});
},
createCart() {
// called from instance-initializer when no prev cart is found
let cart = this.get('store').createRecord('cart');
cart.save().then(response => {
window.localStorage.setItem('cart', JSON.stringify(response));
});
set(this, 'cartObj', cart);
}
Aucun commentaire:
Enregistrer un commentaire