Browse Source

Level 6.2: custom events, syncing model events to display.

Frederic G. MARAND 6 years ago
parent
commit
acd8295bf1
3 changed files with 24 additions and 3 deletions
  1. 9 0
      web/client/src/todoList.js
  2. 11 3
      web/client/src/todoListView.js
  3. 4 0
      web/client/src/todoView.js

+ 9 - 0
web/client/src/todoList.js

@@ -1,6 +1,15 @@
 const TodoList = Backbone.Collection.extend({
   model: TodoItem,
   url: '/server/todos',
+
+  initialize() {
+    this.on('remove', this.hideModel);
+  },
+
+  hideModel(model) {
+    // "hide" is a custom event.
+    model.trigger('hide');
+  },
 });
 
 /* List events:

+ 11 - 3
web/client/src/todoListView.js

@@ -2,6 +2,7 @@
 const TodoListView = Backbone.View.extend({
   initialize() {
     this.collection.on('add', this.addOne, this);
+    this.collection.on('reset', this.addAll, this);
   },
 
   // First attempt (bad) at doing a list render.
@@ -13,6 +14,11 @@ const TodoListView = Backbone.View.extend({
     });
   },
 
+  addAll: function (todoItems) {
+    this.collection.forEach(this.addOne.bind(this));
+    return this;
+  },
+
   addOne: function (todoItem) {
     const todoView = new TodoView({ model: todoItem });
     const rendered = todoView.render();
@@ -21,8 +27,9 @@ const TodoListView = Backbone.View.extend({
 
   render: function () {
     // Now pass the proper context to the loop callback.
-    this.collection.forEach(this.addOne.bind(this));
-    return this;
+    // this.collection.forEach(this.addOne.bind(this));
+    // Or use our new addAll()
+    return this.addAll();
   }
 });
 
@@ -36,9 +43,10 @@ function todoViewListExample(list) {
   console.log(todoListView.el);
   // Apply to the DOM.
   $('#app').html(todoListView.el);
+  return todoListView;
 }
 
 $(function () {
   globalList = todoListFromServer();
-  todoViewListExample(globalList);
+  globalListView = todoViewListExample(globalList);
 });

+ 4 - 0
web/client/src/todoView.js

@@ -28,6 +28,10 @@ const TodoView = Backbone.View.extend({
     // Or without an explicit context, use a bound function.
     // this.model.on('change', this.render.bind(this));
     this.model.on('destroy', this.remove, this);
+
+    // The custom "hide" event says to hide the model from the view, although it
+    // is not destroyed. So we can remove its view.
+    this.model.on('hide', this.remove, this);
   },
 
   // Handle on destroy.