todoModel.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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.desc = todo.description;
  15. delete todo.description;
  16. return todo;
  17. },
  18. toggleStatus(view) {
  19. this.set('status', (this.get('status') === 'incomplete')
  20. ? 'complete'
  21. : 'incomplete');
  22. this.save();
  23. }
  24. }
  25. );
  26. function todoModelSingleExample() {
  27. const onChange = (change, x) => {
  28. console.log('On change', change.changed);
  29. };
  30. // Create a model instance to load it by ID.
  31. const todoItem = new TodoItem({todo: { id: 1 }}, { parse: true });
  32. // Listeners
  33. todoItem.on('change', onChange);
  34. // Skip listener during a change. Notice the value format.
  35. todoItem.set({ 'description': 'some other description' }, {silent: true});
  36. // Remove listener.
  37. todoItem.off('change', onChange);
  38. /* Built-in events
  39. change - when any attribute is modified
  40. change:<attr> - when <attr> is modified
  41. destroy - when the model is destroyed
  42. sync - when the model successfully synced with the server
  43. error - when model save or validation fails
  44. all - on any event
  45. */
  46. // Check default attribute pre-fetch.
  47. const defaultDescription = todoItem.get('description');
  48. // Access the server at /server/todos/1 (urlRoot + '/' + item.id).
  49. const x = todoItem.fetch({ async: false });
  50. // Manipulate attributes.
  51. const description = todoItem.get('description');
  52. todoItem.set('status', 'complete');
  53. // Save on server.
  54. todoItem.save();
  55. // Destroy on server.
  56. // todoItem.destroy();
  57. return todoItem;
  58. }
  59. /**
  60. * @see Model.url
  61. */
  62. $(function () {
  63. // Let it be global for console use.
  64. globalTodoItem = todoModelSingleExample();
  65. });