Browse Source

Level 6.1: rendering collection views, 'add' event.

Frederic G. MARAND 6 years ago
parent
commit
83be441209
4 changed files with 48 additions and 2 deletions
  1. 1 0
      web/client/index.html
  2. 1 1
      web/client/src/todoList.js
  3. 44 0
      web/client/src/todoListView.js
  4. 2 1
      web/client/src/todoView.js

+ 1 - 0
web/client/index.html

@@ -17,5 +17,6 @@
     <script src="lib/todoModel.js"></script>
     <script src="lib/todoList.js"></script>
     <script src="lib/todoView.js"></script>
+    <script src="lib/todoListView.js"></script>
   </body>
 </html>

+ 1 - 1
web/client/src/todoList.js

@@ -79,5 +79,5 @@ function todoListFromServer() {
 
 $(function () {
   // todoListSingleExample(globalTodoItem);
-  globalList = todoListFromServer();
+  // globalList = todoListFromServer();
 });

+ 44 - 0
web/client/src/todoListView.js

@@ -0,0 +1,44 @@
+// Create a view class, just like a model view.
+const TodoListView = Backbone.View.extend({
+  initialize() {
+    this.collection.on('add', this.addOne, this);
+  },
+
+  // First attempt (bad) at doing a list render.
+  renderNaive() {
+    this.collection.forEach(function (todoItem) {
+      const todoView = new TodoView({ model: todoItem });
+      // Problem, "this" is the wrong context is it is needed for rendering.
+      this.$el.append(todoView.render().el);
+    });
+  },
+
+  addOne: function (todoItem) {
+    const todoView = new TodoView({ model: todoItem });
+    const rendered = todoView.render();
+    this.$el.append(rendered.el);
+  },
+
+  render: function () {
+    // Now pass the proper context to the loop callback.
+    this.collection.forEach(this.addOne.bind(this));
+    return this;
+  }
+});
+
+function todoViewListExample(list) {
+  // Note: collection (not model) being passed.
+  const todoListView = new TodoListView({
+    collection: list,
+  });
+
+  todoListView.render();
+  console.log(todoListView.el);
+  // Apply to the DOM.
+  $('#app').html(todoListView.el);
+}
+
+$(function () {
+  globalList = todoListFromServer();
+  todoViewListExample(globalList);
+});

+ 2 - 1
web/client/src/todoView.js

@@ -55,6 +55,7 @@ const TodoView = Backbone.View.extend({
     // $(this.el).html(html);
     // Backbone even gives a shortcut: the $el property.
     this.$el.html(html);
+    return this;
   },
 });
 
@@ -72,5 +73,5 @@ function todoViewSingleExample(todoItem) {
 
 $(function () {
   // Reuse the global item.
-  todoViewSingleExample(globalTodoItem);
+  // todoViewSingleExample(globalTodoItem);
 });