todoView.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. // Create a view class.
  2. const TodoView = Backbone.View.extend({
  3. tagName: 'article',
  4. id: 'todo-view',
  5. className: 'todo',
  6. // Underscore templating.
  7. //language=HTML
  8. template: _.template(`
  9. <h3 class="<%= status %>">
  10. <input type="checkbox"
  11. <% if (status === "complete") print("checked") %> />
  12. <%= description %>
  13. </h3>
  14. `),
  15. events: {
  16. // Generates this.$el.('h3", 'click', alertStatus).
  17. 'click h3': 'alertStatus',
  18. 'change input': 'toggleStatus',
  19. },
  20. // Backbone.
  21. initialize() {
  22. // Backbone on() takes (event, callback, context)
  23. this.model.on('change', this.render, this);
  24. // Or without an explicit context, use a bound function.
  25. // this.model.on('change', this.render.bind(this));
  26. this.model.on('destroy', this.remove, this);
  27. },
  28. // Handle on destroy.
  29. remove() {
  30. this.$el.remove();
  31. },
  32. // Handle "click h3"
  33. alertStatus() {
  34. // Noisy.
  35. // alert('Hey, you clicked the H3');
  36. },
  37. // Handle "change input".
  38. toggleStatus() {
  39. this.model.toggleStatus();
  40. },
  41. render: function () {
  42. const attributes = this.model.toJSON();
  43. const html = this.template(attributes);
  44. // Since this.el is a DOMElement, we can just wrap it with jQuery instead
  45. // of using a jQuery selector like $('#todo-view') or $('.todo').
  46. // This is better because it is id- and class- independent.
  47. // $(this.el).html(html);
  48. // Backbone even gives a shortcut: the $el property.
  49. this.$el.html(html);
  50. },
  51. });
  52. $(function () {
  53. // Create a view instance.
  54. const todoView = new TodoView({ model: todoItem });
  55. // Build view.
  56. todoView.render();
  57. // console.log(todoView.el);
  58. // Apply to the DOM.
  59. $('#app').html(todoView.el);
  60. });