todoListView.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. // Create a view class, just like a model view.
  2. const TodoListView = Backbone.View.extend({
  3. initialize() {
  4. this.collection.on('add', this.addOne, this);
  5. this.collection.on('reset', this.addAll, this);
  6. },
  7. // First attempt (bad) at doing a list render.
  8. renderNaive() {
  9. this.collection.forEach(function (todoItem) {
  10. const todoView = new TodoView({ model: todoItem });
  11. // Problem, "this" is the wrong context is it is needed for rendering.
  12. this.$el.append(todoView.render().el);
  13. });
  14. },
  15. addAll: function (todoItems) {
  16. this.collection.forEach(this.addOne.bind(this));
  17. return this;
  18. },
  19. addOne: function (todoItem) {
  20. const todoView = new TodoView({ model: todoItem });
  21. const rendered = todoView.render();
  22. this.$el.append(rendered.el);
  23. },
  24. render: function () {
  25. // Now pass the proper context to the loop callback.
  26. // this.collection.forEach(this.addOne.bind(this));
  27. // Or use our new addAll()
  28. return this.addAll();
  29. }
  30. });
  31. function todoViewListExample(list) {
  32. // Note: collection (not model) being passed.
  33. const todoListView = new TodoListView({
  34. collection: list,
  35. });
  36. todoListView.render();
  37. console.log(todoListView.el);
  38. // Apply to the DOM.
  39. $('#app').html(todoListView.el);
  40. return todoListView;
  41. }
  42. $(function () {
  43. globalList = todoListFromServer();
  44. globalListView = todoViewListExample(globalList);
  45. });