todos.js 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /**
  2. * @see Model.url
  3. */
  4. $(function () {
  5. const onChange = (...args) => {
  6. console.log('On change', args, TodoItem);
  7. };
  8. // Create a model class.
  9. const TodoItem = Backbone.Model.extend({
  10. defaults: {
  11. description: "Empty todo",
  12. status: "incomplete",
  13. },
  14. // RESTful web service, RoR flavor.
  15. urlRoot: '/server/todos',
  16. });
  17. // Create a model instance to load it by ID.
  18. const todoItem = new TodoItem({ id: 1 });
  19. // Listeners
  20. todoItem.on('change', onChange);
  21. // Skip listener during a change. Notice the value format.
  22. todoItem.set({ 'description': 'some other description' }, {silent: true});
  23. // Remove listener.
  24. //todoItem.off('change', onChange);
  25. /* Built-in events
  26. change - when any attribute is modified
  27. change:<attr> - when <attr> is modified
  28. destroy - when the model is destroyed
  29. sync - when the model successfully synced with the server
  30. error - when model save or validation fails
  31. all - on any event
  32. */
  33. // Check default attribute pre-fetch.
  34. const defaultDescription = todoItem.get('description');
  35. // Access the server at /server/todos/1 (urlRoot + '/' + item.id).
  36. const x = todoItem.fetch({ async: false });
  37. // Manipulate attributes.
  38. const description = todoItem.get('description');
  39. todoItem.set('status', 'complete');
  40. // Save on server.
  41. todoItem.save();
  42. // Destroy on server.
  43. // todoItem.destroy();
  44. // Create a view class.
  45. const TodoView = Backbone.View.extend({
  46. tagName: 'article',
  47. id: 'todo-view',
  48. className: 'todo',
  49. // Underscore templating.
  50. template: _.template('<h3><%= description %></h3>'),
  51. events: {
  52. // Generates this.$el.('h3", 'click', alertStatus).
  53. 'click h3': 'alertStatus',
  54. },
  55. alertStatus() {
  56. alert('Hey, you clicked the H3');
  57. },
  58. render: function () {
  59. const attributes = this.model.toJSON();
  60. const html = this.template(attributes);
  61. // Since this.el is a DOMElement, we can just wrap it with jQuery instead
  62. // of using a jQuery selector like $('#todo-view') or $('.todo').
  63. // This is better because it is id- and class- independent.
  64. // $(this.el).html(html);
  65. // Backbone even gives a shortcut: the $el property.
  66. this.$el.html(html);
  67. },
  68. });
  69. // Create a view instance.
  70. const todoView = new TodoView({ model: todoItem });
  71. // Build view.
  72. todoView.render();
  73. // console.log(todoView.el);
  74. // Apply to the DOM.
  75. $('#app').html(todoView.el);
  76. });