todoModel.js 1.7 KB

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