-
Notifications
You must be signed in to change notification settings - Fork 202
/
Copy pathapp.js
105 lines (95 loc) · 2.8 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import './bootstrap';
import Alpine from 'alpinejs';
import collapse from '@alpinejs/collapse'
import {get, post} from "./http.js";
Alpine.plugin(collapse)
window.Alpine = Alpine;
document.addEventListener("alpine:init", async () => {
Alpine.data("toast", () => ({
visible: false,
delay: 5000,
percent: 0,
interval: null,
timeout: null,
message: null,
type: null,
close() {
this.visible = false;
clearInterval(this.interval);
},
show(message, type = 'success') {
this.visible = true;
this.message = message;
this.type = type;
if (this.interval) {
clearInterval(this.interval);
this.interval = null;
}
if (this.timeout) {
clearTimeout(this.timeout);
this.timeout = null;
}
this.timeout = setTimeout(() => {
this.visible = false;
this.timeout = null;
}, this.delay);
const startDate = Date.now();
const futureDate = Date.now() + this.delay;
this.interval = setInterval(() => {
const date = Date.now();
this.percent = ((date - startDate) * 100) / (futureDate - startDate);
if (this.percent >= 100) {
clearInterval(this.interval);
this.interval = null;
}
}, 30);
},
}));
Alpine.data("productItem", (product) => {
return {
product,
addToCart(quantity = 1) {
post(this.product.addToCartUrl, {quantity})
.then(result => {
this.$dispatch('cart-change', {count: result.count})
this.$dispatch("notify", {
message: "The item was added into the cart",
});
})
.catch(response => {
console.log(response);
this.$dispatch('notify', {
message: response.message || 'Server Error. Please try again.',
type: 'error'
})
})
},
removeItemFromCart() {
post(this.product.removeUrl)
.then(result => {
this.$dispatch("notify", {
message: "The item was removed from cart",
});
this.$dispatch('cart-change', {count: result.count})
this.cartItems = this.cartItems.filter(p => p.id !== product.id)
})
},
changeQuantity() {
post(this.product.updateQuantityUrl, {quantity: product.quantity})
.then(result => {
this.$dispatch('cart-change', {count: result.count})
this.$dispatch("notify", {
message: "The item quantity was updated",
});
})
.catch(response => {
this.$dispatch('notify', {
message: response.message || 'Server Error. Please try again.',
type: 'error'
})
})
},
};
});
});
Alpine.start();