1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- const TodoList = Backbone.Collection.extend({
- model: TodoItem,
- url: '/server/todos',
- });
- /* List events:
- - reset: on fetch() and reset()
- - add: when adding a model to the collection
- - remove: when removing a model from the collection
- Using:
- - todoList.on('reset', () => {}). Can be disabled by passing { silent: true }
- - todoList.off('reset', <same_callback>) to remove it
- - todoList.on('add' (or 'remove'), (modelItem) => { ... })
- Model events are also usable on collections. Triggered on the collection when
- they are triggered on a model within the collection:
- - change : attribute change
- - change:<attr> : specific attribute change
- - destroy : model destroyed
- - sync : model successfully synced
- - error
- - all
- */
- function todoListSingleExample(todoItem) {
- const todoList = new TodoList();
- // Get number of items
- console.log('List length', todoList.length);
- // Push item
- todoList.add(todoItem);
- console.log('List length after add', todoList.length);
- // Get item at index
- const id = todoList.at(0).get('id');
- // Get item by id.
- const item = todoList.get(id);
- console.log(`Item with id ${id} is the added item ?`, item === todoItem);
- todoList.remove(item);
- console.log('List length after remove', todoList.length);
- // todoList.reset([
- // { description: "Pick up milk", status: "incomplete" },
- // { description: "Do the dishes", status: "incomplete" },
- // { description: "Learn backbone", status: "incomplete" },
- // ]);
- //
- // console.log('List after reset', todoList.toJSON());
- todoList.fetch({ async: false });
- console.log('List after fetch', todoList.toJSON());
- return todoList;
- }
- function todoListFromServer() {
- const todoList = new TodoList();
- todoList.fetch({ async: false });
- // Collection forEach is /not/ Array.prototype.forEach.
- todoList.forEach(item => { console.log(item.get('description')); });
- // Not Array.prototype.map.
- const r1 = todoList.map(item => item.get('description'));
- console.log("r1", r1);
- // Returns an Array, not another Collection.
- const r2 = todoList.filter(item => item.get('status') === 'complete');
- console.log("r2", r2, r2.constructor.name);
- // And proxies to 46 Underscore methods.
- // http://backbonejs.org/#Collection-Underscore-Methods
- return todoList;
- }
- $(function () {
- // todoListSingleExample(globalTodoItem);
- // globalList = todoListFromServer();
- });
|