todoModel.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. // Create a model class.
  2. const TodoItem = Backbone.Model.extend({
  3. defaults: {
  4. description: "Empty todo",
  5. status: "incomplete",
  6. },
  7. // RESTful web service, RoR flavor.
  8. urlRoot: '/server/todos',
  9. // Default parse() implementation, not needed with RoR style APIs
  10. // parse: response => response,
  11. // Long format for arrow function to allow breakpoint setting in Chrome.
  12. parse: (response) => {
  13. const todo = response.todo;
  14. todo.description = todo.desc;
  15. delete todo.desc;
  16. return todo;
  17. },
  18. toJSON: function () {
  19. // Default version
  20. // return _.clone(this.attributes);
  21. let attrs = _.clone(this.attributes);
  22. attrs.desc = attrs.description;
  23. attrs = _.pick(attrs, 'desc', 'id', 'status');
  24. return { todo: attrs };
  25. },
  26. toggleStatus(view) {
  27. this.set('status', (this.get('status') === 'incomplete')
  28. ? 'complete'
  29. : 'incomplete');
  30. this.save();
  31. }
  32. }
  33. );
  34. function todoModelSingleExample() {
  35. const onChange = (change, x) => {
  36. console.log('On change', change.changed);
  37. };
  38. // Create a model instance to load it by ID.
  39. const todoItem = new TodoItem({todo: { id: 1 }}, { parse: true });
  40. // Listeners
  41. todoItem.on('change', onChange);
  42. // Skip listener during a change. Notice the value format.
  43. todoItem.set({ 'description': 'some other description' }, {silent: true});
  44. // Remove listener.
  45. todoItem.off('change', onChange);
  46. /* Built-in events
  47. change - when any attribute is modified
  48. change:<attr> - when <attr> is modified
  49. destroy - when the model is destroyed
  50. sync - when the model successfully synced with the server
  51. error - when model save or validation fails
  52. all - on any event
  53. */
  54. // Check default attribute pre-fetch.
  55. const defaultDescription = todoItem.get('description');
  56. // Access the server at /server/todos/1 (urlRoot + '/' + item.id).
  57. const x = todoItem.fetch({ async: false });
  58. // Manipulate attributes.
  59. const description = todoItem.get('description');
  60. todoItem.set('status', 'complete');
  61. // Save on server.
  62. todoItem.save();
  63. // Destroy on server.
  64. // todoItem.destroy();
  65. return todoItem;
  66. }
  67. /**
  68. * @see Model.url
  69. */
  70. $(function () {
  71. // Let it be global for console use.
  72. globalTodoItem = todoModelSingleExample();
  73. });