todoModel.js 1.6 KB

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