todoList.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. const TodoList = Backbone.Collection.extend({
  2. model: TodoItem,
  3. url: '/server/todos',
  4. });
  5. /* List events:
  6. - reset: on fetch() and reset()
  7. - add: when adding a model to the collection
  8. - remove: when removing a model from the collection
  9. Using:
  10. - todoList.on('reset', () => {}). Can be disabled by passing { silent: true }
  11. - todoList.off('reset', <same_callback>) to remove it
  12. - todoList.on('add' (or 'remove'), (modelItem) => { ... })
  13. Model events are also usable on collections. Triggered on the collection when
  14. they are triggered on a model within the collection:
  15. - change : attribute change
  16. - change:<attr> : specific attribute change
  17. - destroy : model destroyed
  18. - sync : model successfully synced
  19. - error
  20. - all
  21. */
  22. function todoListSingleExample(todoItem) {
  23. const todoList = new TodoList();
  24. // Get number of items
  25. console.log('List length', todoList.length);
  26. // Push item
  27. todoList.add(todoItem);
  28. console.log('List length after add', todoList.length);
  29. // Get item at index
  30. const id = todoList.at(0).get('id');
  31. // Get item by id.
  32. const item = todoList.get(id);
  33. console.log(`Item with id ${id} is the added item ?`, item === todoItem);
  34. todoList.remove(item);
  35. console.log('List length after remove', todoList.length);
  36. // todoList.reset([
  37. // { description: "Pick up milk", status: "incomplete" },
  38. // { description: "Do the dishes", status: "incomplete" },
  39. // { description: "Learn backbone", status: "incomplete" },
  40. // ]);
  41. //
  42. // console.log('List after reset', todoList.toJSON());
  43. todoList.fetch({ async: false });
  44. console.log('List after fetch', todoList.toJSON());
  45. return todoList;
  46. }
  47. function todoListFromServer() {
  48. const todoList = new TodoList();
  49. todoList.fetch({ async: false });
  50. // Collection forEach is /not/ Array.prototype.forEach.
  51. todoList.forEach(item => { console.log(item.get('description')); });
  52. // Not Array.prototype.map.
  53. const r1 = todoList.map(item => item.get('description'));
  54. console.log("r1", r1);
  55. // Returns an Array, not another Collection.
  56. const r2 = todoList.filter(item => item.get('status') === 'complete');
  57. console.log("r2", r2, r2.constructor.name);
  58. // And proxies to 46 Underscore methods.
  59. // http://backbonejs.org/#Collection-Underscore-Methods
  60. return todoList;
  61. }
  62. $(function () {
  63. // todoListSingleExample(globalTodoItem);
  64. globalList = todoListFromServer();
  65. });