Advertisement
Guest User

Untitled

a guest
Apr 24th, 2017
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.05 KB | None | 0 0
  1. /**
  2. * Hold the wish presentation logic
  3. *
  4. * Here we add, remove and list Wishes
  5. *
  6. * @param {WishesCollection} wishesCollection - where we manage our wishes
  7. * @constructor
  8. */
  9. let WishesView = function(wishesCollection) {
  10. this.wishesCollection = wishesCollection;
  11. };
  12.  
  13. WishesView.prototype.initEvents = function () {
  14. this.publishers();
  15. this.subscribers();
  16. };
  17.  
  18. /**
  19. * Publish messages on corresponding DOM events
  20. */
  21. WishesView.prototype.publishers = function() {
  22. // Handle wish addition
  23. $('.wish-list .wish-add').on('click', function() {
  24. let name = $('.wish-list input[name="name"]').val();
  25. let price = parseFloat($('.wish-list input[name="price"]').val());
  26.  
  27. // Publish a message with corresponding wish data, that a wish is being added
  28. $.Topic( "wish-add" ).publish( {name, price} );
  29. });
  30.  
  31. // Handle wish remove
  32. $('.wish-list .wish-list-items').on('click', '.wish-remove', function() {
  33. let id = $(this).data('id');
  34.  
  35. // Publish a message with corresponding wish data, that a wish is being removed
  36. $.Topic( "wish-remove" ).publish(id);
  37. });
  38. };
  39.  
  40. /**
  41. * Subscribe wishes view to relevant topics
  42. */
  43. WishesView.prototype.subscribers = function() {
  44. const self = this;
  45.  
  46. $.Topic( "wish-add" ).subscribe( function({name, price}) {
  47. self.render();
  48. });
  49.  
  50. $.Topic( "wish-remove" ).subscribe( function(name) {
  51. self.render();
  52. });
  53. };
  54.  
  55. /**
  56. * Update the DOM according to the wish collection
  57. */
  58. WishesView.prototype.render = function () {
  59. const wishes = this.wishesCollection.getAll();
  60.  
  61. $('.wish-list .wish-list-items').html('');
  62. let html = '';
  63.  
  64. // Build wishes html
  65. wishes.map(wish => {
  66. html += `<li>${wish.name} - ${wish.price} <a data-id="${wish.id}" data-name="${wish.name}" data-price="${wish.price}" class="wish-remove" href="javascript:;">(remove)</a></li>`;
  67. });
  68.  
  69. // Update the wish list and the sum DOM elements
  70. $('.wish-list .wish-list-items').append(html);
  71. $('.wish-list .wish-list-sum').html(this.wishesCollection.getSum());
  72. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement