|
@@ -3,9 +3,28 @@ const TodoList = Backbone.Collection.extend({
|
|
|
url: '/server/todos',
|
|
|
});
|
|
|
|
|
|
-$(function () {
|
|
|
- // Make a global instance
|
|
|
- todoList = new TodoList();
|
|
|
+/* 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);
|
|
@@ -34,4 +53,31 @@ $(function () {
|
|
|
// 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();
|
|
|
});
|