Skip to content

Commit 38976d2

Browse files
committed
JS vote function refactored and unvote functionality added
1 parent 692880c commit 38976d2

File tree

1 file changed

+42
-19
lines changed

1 file changed

+42
-19
lines changed

public/assets/js/app.js

Lines changed: 42 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -2,36 +2,59 @@ $(document).ready(function () {
22

33
var alert = new Alert('#notifications');
44

5-
$('.btn-vote').click(function (e) {
6-
e.preventDefault();
7-
8-
var form = $('#form-vote');
5+
function VoteForm(form, button, buttonRevert) {
96

10-
var button = $(this);
117
var ticket = button.closest('.ticket');
128
var id = ticket.data('id');
13-
149
var action = form.attr('action').replace(':id', id);
10+
var voteCount = ticket.find('.votes-count');
11+
12+
buttonRevert = ticket.find(buttonRevert);
1513

1614
button.addClass('hidden');
1715

18-
$.post(action, form.serialize(), function (response) {
19-
//alert
20-
//update count votes
21-
ticket.find('.btn-unvote').removeClass('hidden');
16+
this.getVotes = function () {
17+
return parseInt(voteCount.text().split(' ')[0]);
18+
};
19+
20+
this.updateCount = function (votes) {
21+
voteCount.text(votes == 1 ? '1 voto' : votes + ' votos');
22+
};
23+
24+
this.submit = function (success) {
25+
$.post(action, form.serialize(), function (response) {
26+
buttonRevert.removeClass('hidden');
27+
success(response);
28+
}).fail(function () {
29+
button.removeClass('hidden');
30+
alert.error('Ocurrió un error :(');
31+
});
32+
};
33+
}
34+
35+
$('.btn-vote').click(function (e) {
36+
e.preventDefault();
37+
38+
var voteForm = new VoteForm($('#form-vote'), $(this), '.btn-unvote');
2239

23-
alert.success('¡Gracias por tu voto!');
40+
voteForm.submit(function (response) {
41+
if (response.success) {
42+
alert.success('¡Gracias por tu voto!');
43+
voteForm.updateCount(voteForm.getVotes() + 1);
44+
}
45+
});
46+
});
2447

25-
var voteCount = ticket.find('.votes-count');
26-
var votos = parseInt(voteCount.text().split(' ')[0]);
27-
votos++;
28-
voteCount.text(votos == 1 ? '1 voto' : votos + ' votos');
48+
$('.btn-unvote').click(function (e) {
49+
e.preventDefault();
2950

30-
}).fail(function () {
31-
//print error message
32-
button.removeClass('hidden');
51+
var voteForm = new VoteForm($('#form-unvote'), $(this), '.btn-vote');
3352

34-
alert.error('Ocurrió un error :(');
53+
voteForm.submit(function (response) {
54+
if (response.success) {
55+
alert.info('Voto eliminado');
56+
voteForm.updateCount(voteForm.getVotes() - 1);
57+
}
3558
});
3659
});
3760

0 commit comments

Comments
 (0)