todoView.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. // The custom "hide" event says to hide the model from the view, although it
  28. // is not destroyed. So we can remove its view.
  29. this.model.on('hide', this.remove, this);
  30. },
  31. // Handle on destroy.
  32. remove() {
  33. this.$el.remove();
  34. },
  35. // Handle "click h3"
  36. alertStatus() {
  37. // Noisy.
  38. // alert('Hey, you clicked the H3');
  39. },
  40. // Handle "change input".
  41. toggleStatus() {
  42. this.model.toggleStatus();
  43. },
  44. render: function () {
  45. const attributes = this.model.toJSON();
  46. const html = this.template(attributes);
  47. // Since this.el is a DOMElement, we can just wrap it with jQuery instead
  48. // of using a jQuery selector like $('#todo-view') or $('.todo').
  49. // This is better because it is id- and class- independent.
  50. // $(this.el).html(html);
  51. // Backbone even gives a shortcut: the $el property.
  52. this.$el.html(html);
  53. return this;
  54. },
  55. });
  56. function todoViewSingleExample(todoItem) {
  57. // Create a view instance.
  58. const todoView = new TodoView({ model: todoItem });
  59. // Build view.
  60. todoView.render();
  61. // console.log(todoView.el);
  62. // Apply to the DOM.
  63. $('#app').html(todoView.el);
  64. }
  65. $(function () {
  66. // Reuse the global item.
  67. // todoViewSingleExample(globalTodoItem);
  68. });